我使用Django REST框架,并使用此库为前端应用程序提供基于令牌的身份验证。
有使用django-allauth
插件的谷歌登录实现。
我想在用户使用社交帐户登录时生成访问令牌。
为了处理社交登录和生成社交帐户,我创建了这个视图。
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_id
和client_secret
。
但这会产生错误
'{"error": "unsupported_grant_type"}'
版本
django-oauth工具包==1.3.0
通过传递client_id
和client_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