首页 > 解决方案 > 如何使用从登录视图中获得的 jwt 令牌进行身份验证

问题描述

我需要创建 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)

标签: pythondjangodjango-rest-framework

解决方案


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

  1. 您的客户端应在每个请求的授权标头中将此令牌发送给 API ,例如:

    Authorization: Bearer your_token
    
  2. 在 api 方面,您需要使用身份验证类,该类查找 Authorization 标头,获取令牌并对其进行解码,如果令牌有效,则找到与令牌关联的用户实例。

如果您使用一个用于 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',
        ...
    ]
}

推荐阅读