我打開這個問題作為最后的手段。
我正在學習 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 的任何有用資訊。
uj5u.com熱心網友回復:
你在authentication_classes這里覆寫:
class StudentList(APIView):
authentication_classes = []
添加JWTAuthentication到該串列中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334386.html
標籤:姜戈 django-rest-framework-simplejwt
上一篇:Django3.2.8自定義中間件回傳302重定向錯誤
下一篇:匿名用戶和登錄用戶的訪問內容
