我如何使用从登录视图获得的jwt令牌进行身份验证

时间:2019-03-22 20:01:55

标签: 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 = (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)

1 个答案:

答案 0 :(得分:0)

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

  1. 您的客户端应在 Authorization 标头中将此令牌随API的每个请求发送给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',
        ...
    ]
}
相关问题