【发布时间】:2020-04-07 18:54:33
【问题描述】:
- 我觉得很难涵盖 DRF_jwt/DRF_oauth2 但是 Django GraphQL JWT 看起来很简单....
- 我可以同时使用它们以方便我吗
- 我是 Rest Framework 的新手
【问题讨论】:
标签: django-rest-framework django-rest-framework-jwt
【问题讨论】:
标签: django-rest-framework django-rest-framework-jwt
如果您的意思是使用 django-graphql-jwt 进行身份验证并使用 DRF 进行其他用户帐户相关操作,例如更新、检索、删除、重置密码...
您可以使用django-graphql-auth。
它扩展了 django-graphql-jwt,并提供了一个完整的 api 来处理用户帐户。
【讨论】:
您可以为 DRF 创建自定义身份验证后端,该后端扩展 rest_framework.authentication.BaseAuthentication 并使用 graphql_jwt.utils 在 DRF 中对用户进行身份验证,方式与 django-graphql-jwt 完全相同它。
这就是我所拥有的:
from graphql_jwt.exceptions import JSONWebTokenError
from graphql_jwt.utils import get_payload, get_user_by_payload
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework import exceptions
class TokenAuthentication(BaseAuthentication):
keyword = 'JWT'
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != self.keyword.lower().encode():
return None
if len(auth) == 1:
msg = 'Invalid token header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid token header. Token string should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
try:
token = auth[1].decode()
except UnicodeError:
msg = 'Invalid token header. Token string should not contain invalid characters.'
raise exceptions.AuthenticationFailed(msg)
try:
payload = get_payload(token)
user = get_user_by_payload(payload)
except JSONWebTokenError as e:
raise exceptions.AuthenticationFailed(str(e))
if user is None or not user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted.')
return (user, None)
def authenticate_header(self, request):
return self.keyword
【讨论】: