0

我正在使用Django REST Framework并使用此库为前端应用程序提供基于令牌的身份验证。

有使用django-allauth插件使用 Google 实现登录。

我想在用户使用社交帐户登录时生成访问令牌。

为了处理社交登录和生成社交帐户,我创建了这个视图。

class GoogleLoginView(LoginView):
    """
    Enable login using google
    """
    adapter_class = GoogleOAuth2Adapter
    serializer_class = CustomSocialLoginSerializer

    def login(self):
        self.user = self.serializer.validated_data['user']
        self.token = TokenView().create_token_response(self.request)
        return self.token

    def post(self, request, *args, **kwargs):
        self.request = request
        self.serializer = self.get_serializer(
            data=self.request.data,
            context={'request': request}
        )
        self.serializer.is_valid(raise_exception=True)

        url, header, body, status_ = self.login()
        return Response(json.loads(body), status=status_)

请求数据与应用程序user一起具有实例。client_idclient_secret

但这会产生错误

'{"error": "unsupported_grant_type"}'

版本
django-oauth-toolkit==1.3.0

4

1 回答 1

0

通过传递社交网络访问令牌client_idclient_secret在视图中附加其他字段来解决它

    def login(self):
        self.user = self.serializer.validated_data['user']

        # Store request
        request = self.request

        # Change request data to mutable
        request.data._mutable = True

        # Add required data to the request
        request.data['grant_type'] = 'password'           # Call Password-owned grant type
        request.data['username'] = self.user.username     # Fake request data to oauth-toolkit
        request.data['password'] = '-'                    # Fake request data to oauth-toolkit
        request.data['social_login'] = True               # Important, if not set will use username, password
        request.data['user'] = self.user                  # Important, assign user obj

        # Change request data to non-mutable
        request.data._mutable = False

        # Generate token
        self.token = TokenView().create_token_response(request)

        return self.token
于 2020-05-12T03:05:50.197 回答