2

I have successfully implemented oauth2 for my django rest api project. I want to change the error response format of the login api.

Current error response is

{
  "error_description": "Invalid credentials given.",
  "error": "invalid_grant"
}

I want to change the error_description key to detail (detail is the key of all other django error responses). I need to make a standardize all the error responses.

Expected result is

{
  "detail": "Invalid credentials given."
}

This is executing from class OAuth2Error(Exception) in /lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/errors.py file.

Arun SS
  • 1,791
  • 8
  • 29
  • 48

1 Answers1

2

I would suggest intercepting this type of response and adapt it as you wish.

There are several ways, but the easiest choice would be to define your own view which is called for the authorization url, which internally calls oauth2 view and modifies response for this case, e.g. something like

from:

from oauth2_provider.views import TokenView
...
    url('auth/token/', TokenView.as_view()),

to:

from oauth2_provider.views import TokenView

def custom_token_view(request, *args, **kwargs):
    response = TokenView.as_view()(request, *args, **kwargs)
    if "invalid_grant " in response.content:
       response = do_whatever_needed(response) # i.e. response.content
    return response 

...
    url('auth/token/', custom_token_view),

More flexible/general solution alternative

If you use Django rest framework (DRF) I would suggest:

  • setting up custom DRF JSON renderer - define your own,
  • your custom renderer should inherit default renderer (rest_framework.renderers.JSONRenderer)
  • in renderer intercept all responses - by calling default render function and detect this particular one (error=invalid_grant) and customize it

If you don't use DRF:

  • create custom middleware
  • if django < 1.10 then check implementing process_response, if django >=1.10 then call method
  • again, intercept all responses and detect only this one, which you can modify as you need
Robert Lujo
  • 15,383
  • 5
  • 56
  • 73