Reputation: 47
I am using django 2.1 and python 3.6 and django rest framework 3.8.2 ... I am trying to find a way to customize the json response when authentication failed.
I am using a third party package Django OAuth Toolkit
The only way I could think of is writing a custom authentication class
{ "detail": "Authentication credentials were not provided." }
{ "Failure": "Authentication credentials were not provided. xyz etc" }
My attempt at overwriting the BaseAuthorizationView
views.py
from django.http import HttpResponse
from oauth2_provider.views.base import TokenView, BaseAuthorizationView
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from oauth2_provider.models import get_access_token_model, get_application_model
class CustomAuthorizationView(BaseAuthorizationView):
def dispatch(self, request, *args, **kwargs):
self.oauth2_data = {}
return super().dispatch(request, *args, **kwargs)
def error_response(self, error, application, **kwargs):
"""
Handle errors either by redirecting to redirect_uri with a json in the body containing
error details or providing an error response
"""
redirect, error_response = super().error_response(error, **kwargs)
if redirect:
return self.redirect(error_response["url"], application)
status = error_response["error"].status_code
return self.render_to_response("hello", status=status)
urls.py
urlpatterns = [
...
url(r"o/authorize/", appointmentViews.CustomAuthorizationView, name="authorize"),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
...
Please let me know if I could provide more information! Thank you in advance.
Upvotes: 0
Views: 528
Reputation: 47
I ended up solving my problem with django rest, custom exception handling link
views.py
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
if response is not None:
response.data['status_code'] = response.status_code
return response
settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'project.apps.utils.exception.custom_exception_handler'
}
where project (folder) > apps (folder) > utils (folder) > exception.py > custom...
response:
{
"detail": "Authentication credentials were not provided.",
"status_code": 401
}
Upvotes: 1