JWT 身份验证 returns Django Rest Framework 中的 AnonymousUser with SimpleJWT

JWT authentication returns AnonymousUser in Django Rest Framework with SimpleJWT

我打开这个问题是不得已的办法。

我正在学习 JWT 并想在我的 django 应用程序上实现它。我没有任何关于 Basic auth 和 Token auth 的问题,但是 JWT 没有验证我的用户...

这是我的 settings.py:

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

这是我的观点:

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)

这是我的 AdminOrTeacherOnly 权限 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 

我能够成功获取刷新和访问令牌:

然后,我将如下添加到 Headers 并发送请求:

在调试器上,当进入权限class:

这里,request.userreturns<django.contrib.auth.models.AnonymousUser object at 0x104f5afd0>

我不知道我错过了什么。查看了相关问题,但找不到有关 SimpleJWT 的任何有用信息。

您在此处覆盖 authentication_classes

class StudentList(APIView):
    authentication_classes = []

JWTAuthentication 添加到该列表。