我正在将Python应用程序从oAuth 1迁移到oAuth 2,该应用程序读取用户的Google日历源 .
- 使用oAuth 1:我的应用程序将打开浏览器,用户可以使用他的GMail帐户进行身份验证并授权访问,我的应用程序将获得该用户的user_token,user_secret,然后对日历提要进行身份验证:
client = gdata.calendar.client.CalendarClient(source='test')
client.auth_token = gdata.gauth.OAuthHmacToken(app_key,
app_secret,user_token,user_secret,gdata.gauth.ACCESS_TOKEN)
这个令牌,秘密对将是长寿 .
- 使用oAuth 2:我在Google API控制台中注册了我的应用并获得了oAuth 2 client_id和client_secret,并修改了应用以请求用户的access_token,来自https://accounts.google.com/o/oauth2/token的refresh_token_对于GData lib,我应用了此处指定的gauth.py补丁:http://codereview.appspot.com/4440067/
这个access_token很短暂 .
我玩了一点点这里发布的代码http://codereview.appspot.com/4440067/并且工作正常 .
我的问题:
- 我通过我的应用程序的curl调用获取access_token,refresh_token,我可以成功检索两者 . 但是,当我将它应用于此代码时:
token =
gdata.gauth.OAuth2Token(client_id=client_id,client_secret=client_secret',
scope='https://www.google.com/calendar/
feeds',user_agent='calendar-cmdline-sample/1.0')
uri = token.generate_authorize_url()
token.get_access_token(access_token)
它给了我:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/gdata/gauth.py", line 1267,
in get_access_token
raise OAuth2AccessTokenError(error_msg)
gdata.gauth.OAuth2AccessTokenError
- 假设我可以成功完成上述操作,我可以在DB中保存访问/刷新令牌 . 使用python gdata lib,如何使用refresh_token请求另一个access_token(因此每次使用应用程序授权访问时都不必询问用户)
非常感谢提前!
中号
1 回答
Marchie,
我没有看到您的堆栈跟踪的其余部分,但可以给出三个特定问题,相应的解决方案将解决您的整体问题 .
Problem I :未在对象上设置值
redirect_uri
.请注意如何在
get_access_token
中指定请求正文:这取决于在对象上设置的
redirect_uri
属性,该属性最初在generate_authorize_url
中设置 . 因此,在通过调用重建令牌之后您只需要设置重定向URI:
Problem II :
redirect_uri
的默认值不正确(更具体地说,不建议使用) .由于您在没有参数的情况下调用
generate_authorize_url
,因此使用了redirect_uri
的默认值,该值当前为oob
. 作为OAuth 2.0 docs状态,oob
不在支持的值中(已弃用) .如果您确实使用的是已安装的应用程序,则需要将其设置为
此外,当您调用
generate_authorize_url
获取初始标记时,您需要将其用作关键字参数Problem III :您使用不正确的值(也是未在代码段中实例化的值)调用
get_access_token
.您应该使用授权后收到的代码的字符串值或使用
'code'
作为键的字典来调用它 .这可以通过以下方式完成:
Post Script :patch的作者也发布了使用补丁的blog post . (注意,在
generate_authorize_url
函数中使用关键字redirect_url
而不是redirect_uri
时,帖子中会出现拼写错误 . )