2016-07-27 118 views
0

After failing to authenticate for Google Server to Server Applications using Python Oauthlib,我现在尝试直接生成pyjwt的智威汤逊然后用卷曲测试它在Google documentation规定,但它不工作,要么因为我现在得到:无效的智威汤逊:令牌必须是短暂的令牌,并在合理的时间范围内无效JWT与pyjwt的谷歌服务器到服务器应用程序

在Python 3的代码安装pyjwt后:

>>> from datetime import datetime, timedelta 

>>> import json 
>>> import jwt 

>>> json_file = json.load(open("google-project-credentials.json")) 
>>> dt_now = datetime.datetime.utcnow() 
>>> payload = { 'iss' : json_file['client_email'], 'scope' : 'https://www.googleapis.com/auth/tasks', 'aud' : 'https://www.googleapis.com/oauth2/v4/token', 'exp' : int((dt_now + datetime.timedelta(hours=1)).timestamp()), 'iat': int(dt_now.timestamp()) } 
>>> jwt.encode(payload, json_file['private_key'], algorithm='RS256') 
b'PYJWT_RESULT_HERE' 

然后,谷歌文档中所述,我跑在bash卷曲并粘贴前面的结果:

$ curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=PYJWT_RESULT_HERE' https://www.googleapis.com/oauth2/v4/token 

然后我收到以下错误:

{ 
    "error": "invalid_grant", 
    "error_description": "Invalid JWT: Token must be a short-lived token and in a reasonable timeframe" 
} 

我在做什么错?

谢谢!

回答

0

其实,错误消息指出,问题是在被错误地产生了划时代(我不完全理解为什么至今):

>>> from datetime import datetime 
>>> from calendar import timegm 
>>> import json 
>>> import jwt 

>>> json_file = json.load(open("google-project-credentials.json")) 
>>> payload = { 'iss' : json_file['client_email'], 'scope' : 'https://www.googleapis.com/auth/tasks', 'aud' : 'https://www.googleapis.com/oauth2/v4/token', 'exp' : timegm(datetime.utcnow().utctimetuple()) + 600, 'iat' : timegm(datetime.utcnow().utctimetuple()) } 
>>> jwt.encode(payload, json_file['private_key'], algorithm='RS256') 
b'PYJWT_RESULT_HERE' 

然后在猛砸控制台:

$ curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=PYJWT_RESULT_HERE' https://www.googleapis.com/oauth2/v4/token 
{ 
    "access_token": "GOOGLE_ACCESS_TOKEN_YEAH", 
    "token_type": "Bearer", 
    "expires_in": 3600 
} 

我真的很惊讶没有得到更多的帮助,因为我认为谷歌会参与;-(在开源项目上,支持其实更好!

相关问题