django-rest-framework中的JWT身份验证问题 [英] Problem with JWT authentication in django-rest-framework

查看:444
本文介绍了django-rest-framework中的JWT身份验证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用django-rest-knox进行JWT身份验证时遇到了问题.

I have a problem with JWT authentication using django-rest-knox.

错误是: Detail: Authentication credentials were not provided.

ENDPOINT: /api/auth/login/

POST请求中指向端点的标头: { Content-Type: application/json }

Headers in the POST request to the endpoint: { Content-Type: application/json }

正文:

{
    "username": "admin",
    "password": 1234
}

登录API视图:

class UserLoginAPIView(generics.GenericAPIView):
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        token = AuthToken.objects.create(user)
        return Response({
            "user": UserSerializer(user,
                                   context=self.get_serializer_context()).data,
            "token": token
        })

序列化器:

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()


    def validate(self, data):
        user = authenticate(**data)
        if user and user.is_active:
            return user
        raise serializers.ValidationError("Invalid Credentials")

默认设置:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'knox.auth.TokenAuthentication',
    ]
}

推荐答案

我认为您的过程有误.根据Knox文档,您需要提供访问权限登录端点.但是您没有授予访问登录端点的权限. 所以您的登录端点看起来像这样,

I think your procedure is wrong. According to Knox documents, You need to give an access permission login endpoint. But you did not give permission to access your login endpoint. So your login endpoint looks like this,

# views.py 
from django.contrib.auth import login
from rest_framework import permissions
from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.views import LoginView as KnoxLoginView

class LoginView(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        return super(LoginView, self).post(request, format=None)

# settings.py 
REST_KNOX = {
  'USER_SERIALIZER': 'knox.serializers.UserSerializer',
}

如果您在设置中使用用户序列化程序,则会获得带有请求用户的用户名的令牌,例如波纹管

If you use the user serializer in your setting you get token with the username of the requesting user like bellow

{"user":{"username":"admin"},"token":"00bd2a5e517800b75a8f36bbf3baea4c839169108b25a5a5ea599a4ecda974c0"}

更多详细信息在这里. 诺克斯

More details here. Knox

这篇关于django-rest-framework中的JWT身份验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆