令牌认证后Django Rest Framework注销不起作用

时间:2018-08-18 08:28:01

标签: django-rest-framework jwt

我已经成功在django rest框架中使用令牌身份验证机制进行身份验证,但是当我调用注销功能时,它显示错误'AnonymousUser'对象没有属性'auth_token',不知道为什么返回AnonymousUser。

## Serializer ##
class AdminLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        username = data.get("username", "")
        password = data.get("password", "")

        if username and password:
            user = authenticate(username=username, password=password)
            if user:
                if user.is_active:
                    data["user"] = user
                else:
                    msg = 'User is deactivated'
                    raise exceptions.ValidationError(msg)
            else:
                msg = "Unable to login with given credentials"
                raise exceptions.ValidationError(msg)
        else:
            msg = 'Must Provide Username and password'
            raise exceptions.ValidationError(msg)
        return data

## Viewsets ##

class AdminLoginView(APIView):
    def post(self, request):
        serializer = AdminLoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        # django_login(request, user)
        token, created = Token.objects.get_or_create(user=user)
        return Response({"token": token.key, 'id': token.user.id}, status=200)


class AdminLogoutView(APIView):
    authentication_classes = [TokenAuthentication]

    def post(self, request):
        # django_logout(request)
        **request.user.auth_token.delete()**
        return Response(status=204)

1 个答案:

答案 0 :(得分:0)

我认为您没有在loginView的新请求中提供从logoutView获得的令牌。因此TokenAuthentication用匿名用户填充request.user

向您的LogoutViet添加IsAuthenticated权限类,以防止未经身份验证的用户。

from rest_framework import permissions
class AdminLogoutView(APIView):
    permission_classes = [permissions.IsAuthenticated]

另外,检查TokenAuthentication例程,然后将令牌完全像这样放在请求中。您应该以这种模式在Authorization HTTP标头中传递令牌,例如:

Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a