Django 使用 Allauth 进行其余身份验证

2023-11-23

我已经用 Allauth 实现了 django Rest auth,如果我通过 google 登录,它工作正常access_token但有一种情况,某些客户端设备需要通过谷歌登录id_token。 如果我使用,我会收到错误id_token代替access_token

{
  "non_field_errors": [
    "Incorrect value"
  ]
}

请帮帮我


更新您的文件,例如

../allauth/socialaccount/providers/google/provider.py:

class GoogleProvider(OAuth2Provider):
    ....

    def extract_uid(self, data):
        try:
            return str(data['id'])
        except KeyError:
            return str(data['user_id'])

../allauth/socialaccount/providers/google/views.py:

class GoogleOAuth2Adapter(OAuth2Adapter):
    provider_id = GoogleProvider.id
    access_token_url = 'https://accounts.google.com/o/oauth2/token'
    authorize_url = 'https://accounts.google.com/o/oauth2/auth'
    profile_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    token_url = 'https://www.googleapis.com/oauth2/v1/tokeninfo'

    def complete_login(self, request, app, token, **kwargs):
        if 'rest-auth/google' in request.path:
            print('rest-auth api')
            # /api/rest-auth/google
            # but not for website login with google
            resp = requests.get(self.token_url,
                            params={'id_token': token.token,
                                    'alt': 'json'})
        else:
            print('else else rest-auth api')
            resp = requests.get(self.profile_url,
                            params={'access_token': token.token,
                                    'alt': 'json'})
        resp.raise_for_status()
        extra_data = resp.json()
        login = self.get_provider() \
            .sociallogin_from_response(request,
                                   extra_data)
        return login


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

对于使用 id_token,您将仅获得这些字段(access_type、audience、email、email_verified、expires_in、issued_at、issued_to、issuer、nonce、scope、user_id、verified_email)。所以如果你的用户表需要phone and name你可以将其设置为空name=''等等。为此,您可以使用以下代码。

将用户模型必填字段设置为空以进行覆盖id_token case

这取决于您的用户模型,在我的情况下,我们需要电话和姓名,所以我将它们设置为空。如果不这样做,您将收到失败的约束错误。

../allauth/socialaccount/providers/base.py

class Provider(object):
    def sociallogin_from_response(self, request, response):
        ....
        common_fields = self.extract_common_fields(response)
        common_fields['name'] = common_fields.get('name', '')
        common_fields['phone'] = common_fields.get('phone', '')
        common_fields['username'] = uid
        ....

我已将用户名设置为从社交平台api获取的用户id。后来我强迫用户更新其详细信息(用户名、姓名、电话等)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django 使用 Allauth 进行其余身份验证 的相关文章

随机推荐