使用用户实例生成访问令牌(不是用户名、密码和 grant_type)

Generate access token using user instance (not username, password and grant_type)

我正在使用 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

通过将 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