Reputation: 881
I am new to django. I have a project that mobiles can have interaction with server using a token. In settings.py I have:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'UPLOADED_FILES_USE_URL': False,
'DEFAULT_PAGINATION_CLASS': None,
'PAGE_SIZE': DEFAULT_PAGE_SIZE, # For views using PageNumberPagination
}
but when using postman I send a request with an invalid token, istead of 401 (unauthorized), 403 (forbidden) is returning. Is there anything special I can do to fix this?
tnx
Upvotes: 1
Views: 387
Reputation: 1239
You still can define a custom exception handler that would send a HTTP_401_UNAUTHORIZED
exception when AuthenticationFailed
or NotAuthenticated
exceptions occur.
You can do it like so (from this answer on a GitHub issue):
from rest_framework import exceptions
from rest_framework import status
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
response = exception_handler(exc, context)
if isinstance(exc, (exceptions.AuthenticationFailed, exceptions.NotAuthenticated)):
response.status_code = status.HTTP_401_UNAUTHORIZED
return response
and configure it in your REST_FRAMEWORK
settings :
REST_FRAMEWORK = {
# ...
'EXCEPTION_HANDLER': 'path.to.your.custom_exception_handler',
# ...
}
Upvotes: 1
Reputation: 20976
As stated by the documentation:
The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response.
Adds this extract from SessionAuthentication
Unauthenticated responses that are denied permission will result in an HTTP 403 Forbidden response.
And you have your answer.
Either move TokenAuthentication
as first DEFAULT_AUTHENTICATION_CLASSES
or document the current behavior.
Upvotes: 2