簡體   English   中英

JWT 身份驗證使用 SimpleJWT 在 Django Rest Framework 中返回 AnonymousUser

[英]JWT authentication returns AnonymousUser in Django Rest Framework with SimpleJWT

我打開這個問題作為最后的手段。

我正在學習 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 的任何有用信息。

你在這里覆蓋authentication_classes

class StudentList(APIView):
    authentication_classes = []

JWTAuthentication添加到該列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM