【问题标题】:JWT authentication returns AnonymousUser in Django Rest Framework with SimpleJWTJWT 身份验证在带有 SimpleJWT 的 Django Rest Framework 中返回 AnonymousUser
【发布时间】:2021-10-23 18:16:32
【问题描述】:

我将这个问题作为最后的手段。

我正在学习 JWT,并希望在我的 django 应用上实现它。我对基本身份验证和令牌身份验证没有任何问题,但 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 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,如下所示并发送请求:

在调试器上,当它进入权限类时:

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

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

【问题讨论】:

    标签: django django-rest-framework-simplejwt


    【解决方案1】:

    你在这里覆盖了authentication_classes

    class StudentList(APIView):
        authentication_classes = []
    

    JWTAuthentication 添加到该列表中。

    【讨论】:

    • 这是一个了不起的答案!很遗憾在互联网上找不到这样的东西。顺便说一句,我必须补充一点,删除 authentication_classes 并没有帮助,但将 JWTAuthentication 添加到列表中可以解决问题。
    • 很高兴为您提供帮助,我编辑了我的答案
    猜你喜欢
    • 2021-09-09
    • 2019-01-01
    • 2021-04-11
    • 2020-04-10
    • 2015-06-01
    • 2019-07-29
    • 2017-12-23
    • 2020-03-22
    • 2019-11-20
    相关资源
    最近更新 更多