sachin developer
sachin developer

Reputation: 41

Django Rest Framework logout not working after token authentication

I had succeeded in making authentication with token authentication mechanism in django rest framework but when i call logout function it showing error 'AnonymousUser' object has no attribute 'auth_token', don't know why it returning 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)

Upvotes: 2

Views: 2661

Answers (1)

Ehsan Nouri
Ehsan Nouri

Reputation: 2040

I think you are not providing the token you have got from the loginView in the new request to logoutView. so the TokenAuthentication fills the request.user with AnonymousUser.

add the IsAuthenticated permission class to your LogoutViet to prevent the unauthenticated users.

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

also, check the TokenAuthentication routine, and put the token in the requests exactly like that. you should pass the token in Authorization HTTP header in a pattern like this for example:

Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a

Upvotes: 1

Related Questions