Python 如何使用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

我需要创建JWT令牌身份验证,但我不知道如何创建,您能解释一下如何做得更好,或者举一些例子吗

我的看法是:

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)

您正在该视图中创建令牌。之后,还需要另外两种机制:

  • 您的客户端应在每个请求中在授权标题中向API发送此令牌,如:

    Authorization: Bearer your_token
    
  • 在api方面,您需要使用一个身份验证类,该类查找授权头,获取令牌并对其进行解码,如果令牌有效,则查找与令牌关联的用户实例
  • 如果您使用库进行drf jwt身份验证,那么它应该有一个您可以使用的身份验证类。如果您是手动实现的,那么您需要自己编写一个身份验证类,该类为DRF的BaseAuthentication类的子类。基本上可以是这样的:

    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',
            ...
        ]
    }
    

    您正在该视图中创建令牌。之后,还需要另外两种机制:

  • 您的客户端应在每个请求中在授权标题中向API发送此令牌,如:

    Authorization: Bearer your_token
    
  • 在api方面,您需要使用一个身份验证类,该类查找授权头,获取令牌并对其进行解码,如果令牌有效,则查找与令牌关联的用户实例
  • 如果您使用库进行drf jwt身份验证,那么它应该有一个您可以使用的身份验证类。如果您是手动实现的,那么您需要自己编写一个身份验证类,该类为DRF的BaseAuthentication类的子类。基本上可以是这样的:

    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',
            ...
        ]
    }
    
    检查此程序包:检查此程序包: