JWT令牌认证-生成令牌

时间:2019-08-14 09:09:40

标签: django-rest-framework

我已创建一个使用用户名和密码登录的登录屏幕。我有一个jwt身份验证,但是我有点困惑,因为我有两个登录URL,而我只想要一个。 jwt url为我提供了令牌,而我创建的另一个我可以登录但没有令牌生成。这是我的代码:

serializers.py

class UserLoginSerializer(ModelSerializer):
    token = CharField(allow_blank=True, read_only=True)
    username = CharField(required=False, allow_blank=True)
    class Meta:
        model = User
        fields = [
            'username',
            'password',
            'token',
        ]
        extra_kwargs = {"password":{"write_only": True}} 

    def validate(self, data):
        user = authenticate(**data)
        if user:
            if user.is_active:
                data['user'] = user
                return data
            raise exceptions.AuthenticationFailed('Account is not activated')
        raise exceptions.AuthenticationFailed('User is not active')

    def validate(self, data):
        user_obj = None
        username = data.get("username", None)
        password = data["password"]
        if not username:
            raise ValidationError("A username is required")
        user = User.objects.filter(
                Q(username=username) 
            ).distinct()
        if user.exists() and user.count() == 1:
            user_obj = user.first()
        else:
            raise ValidationError("This username is not valid")
        if user_obj:
            if not user_obj.check_password(password):
                raise ValidationError("Incorrect credentials, please try again")
        data["token"] = "SOME RANDOM TOKEN"
        return data

views.py

class UserLoginAPIView(APIView):
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer
    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

您可以像这样重新编写登录序列化器:

from rest_framework_jwt.serializers import JSONWebTokenSerializer

class SignInJWTSerializer(JSONWebTokenSerializer):

        def validate(self, attrs):

            email    = attrs.get('email')
            password = attrs.get('password')

            if email is None or password is None:
                message = 'Must include email and password'
                raise serializers.ValidationError({'message': message})

            ...

在网址中:

from rest_framework_jwt.views import ObtainJSONWebToken

path('login/', ObtainJSONWebToken.as_view(serializer_class=serializers.SignInJWTSerializer), name='login'),

还删除视图类