Home > Enterprise >  JWT authentication returns AnonymousUser in Django Rest Framework with SimpleJWT
JWT authentication returns AnonymousUser in Django Rest Framework with SimpleJWT

Time:10-24

I am opening this question as a last resort.

I am learning JWT and want to implement it on my django app. I didn't have any issues regarding Basic auth and Token auth, but JWT doesn't authenticate my user...

This is my settings.py:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
        'api.permissions.AdminOrTeacherOnly'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ]
}

This is my view:

class StudentList(APIView):

    authentication_classes = []
    permission_classes = [AdminOrTeacherOnly]

    def get(self, request, format=None):
        students = Student.objects.all()
        serializer = StudentListSerializer(students, many=True)

        if not serializer.data:
            return Response(status=status.HTTP_204_NO_CONTENT)

        return Response(serializer.data, status=status.HTTP_200_OK)

This is my AdminOrTeacherOnly permission class:

class AdminOrTeacherOnly(permissions.BasePermission):
    """
    Object-level permission to only allow teachers of a student to edit.
    Assumes the model instance has an `owner` attribute.
    """
    message = 'Only admin or teacher can edit student detail.'

    def has_permission(self, request, view):
        # Only teacher and/or admin user will be able to,
        # edit and/or list this view.
        is_staff = bool(request.user and request.user.is_staff)
        is_teacher_group = str(request.user.groups.all().first()) == 'teacher'

        return is_staff or is_teacher_group 

I am able to get refresh and access token successfully:

enter image description here

Then, I am adding this to Headers as follows and send a request:

enter image description here

On debugger, when it enters the permission class:

enter image description here

Here, request.user returns <django.contrib.auth.models.AnonymousUser object at 0x104f5afd0>

I don't know what I am missing. Looked at related questions but couldn't find anything helpful regarding the SimpleJWT.

CodePudding user response:

You're overriding authentication_classes here:

class StudentList(APIView):
    authentication_classes = []

Add JWTAuthentication to that list.

  • Related