django-allauth在回调时禁止403

时间:2014-02-12 20:34:34

标签: django django-allauth

我正在创建一个自定义提供程序来从另一个内部项目获取oauth2令牌,这个过程几乎没问题,但是当浏览器使用此url返回我的项目时出现403 forbidden错误:

http://localhost:8001/account/connect/login/callback/?state=Nngd5Gu3JnB4&code=Rqqg91oEwQKDsvSyzZ8Az5fEeHGaEe#_=_

这是我的自定义提供程序中的views.py:

import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView)
from .provider import ConnectProvider


class ConnectOAuth2Adapter(OAuth2Adapter):
    provider_id = ConnectProvider.id
    access_token_url = 'http://localhost:8000/o/token/'
    authorize_url = 'http://localhost:8000/o/authorize/'
    profile_url = 'http://localhost:8000/api/account/'

    def complete_login(self, request, app, token, **kwargs):
        _token = {'access_token':token.token}
        resp = requests.get(self.profile_url, params={'access_token': token.token, 'alt': 'json'})
        extra_data = resp.json()
        login = self.get_provider().sociallogin_from_response(request, extra_data)
        return login

oauth2_login = OAuth2LoginView.adapter_view(GoConnectOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(GoConnectOAuth2Adapter)

1 个答案:

答案 0 :(得分:4)

在浏览了allauth源代码后,我发现问题是由于session:

 @classmethod
  def stash_state(cls, request):  
      state = cls.state_from_request(request) 
      verifier = get_random_string()  
      request.session['socialaccount_state'] = (state, verifier)
      return verifier



@classmethod
  def verify_and_unstash_state(cls, request, verifier):
      if 'socialaccount_state' not in request.session:
          raise PermissionDenied()        
      state, verifier2 = request.session.pop('socialaccount_state')
      if verifier != verifier2:       
          raise PermissionDenied()        
      return state

基本上我有2个网站,一个是OAuth服务器(localhost:8000),另一个是OAuth客户端(localhost:8001),最初客户端用stash_state方法设置会话,然后浏览器重定向到服务器,但由于两者都使用相同的域名,服务器会覆盖会话并清除客户端设置的会话。