DRF does not consider all authenticators when deciding whether to raise a 401 or 403. #9561
Replies: 1 comment 2 replies
-
A colleague came across the following in docs: https://www.django-rest-framework.org/api-guide/authentication/#unauthorized-and-forbidden-responses So it looks like this is intentional. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Following the documentation on setting authentication classes, we have configured two authentication classes in a project I work on.
Within our code, we raise
rest_framework.exceptions.AuthenticationFailed
which we expect to raise a 401. However, it raises a 403.Digging into the source code, I find that
rest_framework.views.APIVIew.handle_exception
attaches theHTTP_403_FORBIDDEN
status onto the exception. This happens due torest_framework.views.APIVIew.get_authenticate_header
returningNone
.I believe there might be a bug in that function. That function does the following:
The first authenticator's
authenticate_header
method does not return anything. However, if we change the function to use the second authenticator class (authenticators[1]
), it instead returns a string. Subsequently, the response then contains a 401 status code.I believe the fix would be something like:
I am happy to raise an issue and apply the fix if you agree.
Note: A colleague has checked the tests and it seems that the tests all assume there is always a single authentication class.
Beta Was this translation helpful? Give feedback.
All reactions