Estoy abriendo esta pregunta como último recurso.
Estoy aprendiendo JWT y quiero implementarlo en mi aplicación django. No tuve ningún problema con la autenticación básica y la autenticación de token, pero JWT no autentica a mi usuario...
Esta es mi configuración.py:
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'api.permissions.AdminOrTeacherOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] }Esta es mi vista:
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)Esta es mi clase de permiso 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_groupPuedo actualizar y acceder al token con éxito:
Luego, agrego esto a los Headers de la siguiente manera y envío una solicitud:
En el depurador, cuando ingresa a la clase de permiso:
Aquí, request.user devuelve <django.contrib.auth.models.AnonymousUser object at 0x104f5afd0>
No sé lo que me estoy perdiendo. Miré preguntas relacionadas pero no pude encontrar nada útil con respecto a SimpleJWT.
Está anulando las clases de authentication_classes aquí:
class StudentList(APIView): authentication_classes = [] Agregue JWTAuthentication a esa lista.