[英]Customizing JWT response from django-rest-framework-simplejwt
[英]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.