DRF Viewset authentication class is not working properly #8378
-
ProblemDRF ModelViewSet is not authenticating a request through all classes, instead it directly calls view after first authentication class. Steps to ReproduceCode not be considered exact, it's abstract form of my working code UserAuthenticationclass UserAuthentication(authentications.BaseAuthentication):
def authenticate(self, request):
print("Doing user auth")
if not "X_TOKEN" in request.META:
return None
try:
user = User.objects.get(token=request.META.get("X_TOKEN")
except User.DoesNotExists:
raise expectipons.AuthenticationFailed(detail="No user found")
setattr(request, "user", user)
return (user, None)
ProjectAuthenticationclass ProjectAuthentication(authentications.BaseAuthentication):
def authenticate(self, request):
print("Doing project auth")
if not hasattr(request, "user"):
return None
try:
project = Project.objects.get(user=request.user)
except Project.DoesNotExists:
raise expectipons.AuthenticationFailed(detail="No project found")
setattr(request, "project", project)
return (project, None)
The viewsetsclass ProjectViewset(ModelViewSet):
authentication_classes = [UserAuthentication, ProjectAuthenticaion]
.....
class ProjectViewsetRever(ModelViewSet):
authentication_classes = [ProjectAuthentication, UserAuthentication]
.... Test stdout[ProjectViewset]
Doing user auth
[ProjectViewsetRever]
Doing project auth |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
After going through documentation and source code of DRF, I understood it's an architecture decision. Authentication class will traverse through the Instead like permission_classes which works like |
Beta Was this translation helpful? Give feedback.
After going through documentation and source code of DRF, I understood it's an architecture decision. Authentication class will traverse through the
authentication_classes
list until it receive expected (user, auth) tuple, and will stop traversal immediately after the first auth class providing such values.Instead like permission_classes which works like
perm_class_A && perm_class_B && perm_class_C
. Auth classes works likeauth_class_A || auth_class_B || auth_class_C