我正在使用python-social-auth,当我尝试刷新Google Oauth2访问令牌时,我收到以下错误:
[2017-02-15 14:41:00,089: ERROR/MainProcess] Task tasks.tasks.test_login[169e5810-489d-4134-af8f-db3b80629fd2] raised unexpected: HTTPError(u'400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token',)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/home/paulozullu/dev/workspaces/wopik/wopik/tasks/tasks.py", line 1928, in test_login
social.refresh_token(strategy)
File "/usr/local/lib/python2.7/dist-packages/social/storage/base.py", line 54, in refresh_token
response = backend.refresh_token(token, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/social/backends/oauth.py", line 418, in refresh_token
request = self.request(url, **request_args)
File "/usr/local/lib/python2.7/dist-packages/social/backends/base.py", line 225, in request
response.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 909, in raise_for_status
raise HTTPError(http_error_msg, response=self)
HTTPError: 400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token
我使用以下代码刷新访问令牌:
from social.apps.django_app.utils import load_strategy
w_user = WUser.objects.get(auth_user=A('username','xxxx'))
social = UserSocialAuth.objects.get(user_id=w_user.auth_user.id)
strategy = load_strategy()
social.refresh_token(strategy)
我做错了吗?
答案 0 :(得分:1)
致电social.get_access_token(load_strategy())
时遇到相同的问题。如果您不想手动实施Google登录,则可以使用这种解决方法,它迫使用户重新进行身份验证以刷新其令牌。
try:
strategy = load_strategy()
access_token = social.get_access_token(ls)
except HTTPError as e:
return HttpResponseRedirect(reverse('social:begin', kwargs={'backend': "google-oauth2"}))
答案 1 :(得分:0)
正如上面的yilmazhuseyin所指出的,该问题与刷新令牌不存在有关。您需要在参数中传递access_type='offline'
,以便Google返回刷新令牌。可以通过在settings.py
中为django中的python-social-auth添加以下内容来实现:
SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {
'access_type': 'offline',
}
更多详细信息可以在Google OAuth 2.0 documentation中找到。