Python 如何使用jwt令牌进行从登录视图获得的身份验证
我需要创建JWT令牌身份验证,但我不知道如何创建,您能解释一下如何做得更好,或者举一些例子吗 我的看法是:Python 如何使用jwt令牌进行从登录视图获得的身份验证,python,django,django-rest-framework,Python,Django,Django Rest Framework,我需要创建JWT令牌身份验证,但我不知道如何创建,您能解释一下如何做得更好,或者举一些例子吗 我的看法是: class UserLogin(generics.CreateAPIView): """ POST auth/login/ """ # This permission class will overide the global permission # class setting permission_classes = (permissio
class UserLogin(generics.CreateAPIView):
"""
POST auth/login/
"""
# This permission class will overide the global permission
# class setting
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
serializer_class = TokenSerializer
def post(self, request, *args, **kwargs):
username = request.data.get("username", "")
password = request.data.get("password", "")
user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response({
"token": jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
}, status=200)
return Response(status=status.HTTP_401_UNAUTHORIZED)
您正在该视图中创建令牌。之后,还需要另外两种机制:
Authorization: Bearer your_token
class JwtAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION')
if auth_header:
key, token = auth_header.split(' ')
if key == 'Bearer':
# Decode the token here. If it is valid, get the user instance associated with it and return it
...
return user, None
# If token exists but it is invalid, raise AuthenticationFailed exception
# If token does not exist, return None so that another authentication class can handle authentication
您需要告诉DRF使用此身份验证类。将以下内容添加到您的设置文件:
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': [
'path.to.JwtAuthentication',
...
]
}
您正在该视图中创建令牌。之后,还需要另外两种机制:
Authorization: Bearer your_token
class JwtAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION')
if auth_header:
key, token = auth_header.split(' ')
if key == 'Bearer':
# Decode the token here. If it is valid, get the user instance associated with it and return it
...
return user, None
# If token exists but it is invalid, raise AuthenticationFailed exception
# If token does not exist, return None so that another authentication class can handle authentication
您需要告诉DRF使用此身份验证类。将以下内容添加到您的设置文件:
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': [
'path.to.JwtAuthentication',
...
]
}
检查此程序包:检查此程序包: