Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom response Headers to APIException

I have created a custom exception referring to http://django-rest-framework.org/api-guide/exceptions.html.

Please know that I have my own authentication backend. Hence I am not using rest_framework's authentication module.

For authentication errors, I want to add 'WWW-Authenticate: Token' header to the response that is sent from the exception.

Any ideas will be very helpful.

Update:

Thanks @Pathétique, This is what I ended up doing.

-Have a base view class named BaseView.

-override the handle_exception method to set appropriate headers, in my case 'WWW-Authenticate'.

Here is the code:

class BaseView(APIView):
  def handle_exception(self, exc):
     if isinstance(exc, MYEXCEPTION):
        self.headers['WWW-Authenticate'] = "Token"
        return Response({'detail': exc.detail,
                        status=exc.status_code, exception=True)

Your thoughts?

like image 445
ubhisat Avatar asked Aug 15 '13 22:08

ubhisat


2 Answers

Try overriding finalize_response in your rest framework view:

def finalize_response(self, request, *args, **kwargs):
    response = super(SomeAPIView, self).finalize_response(request, *args, **kwargs)
    response['WWW-Authenticate'] = 'Token'
    return response

Edit:

After seeing your update, I think your override of handle_exception should work, I would only add an else statement to call the parent method to cover other exceptions. One thing I noticed in overriding dispatch, which may not be an issue here, is that setting a new key/value for self.headers resulted in a server error that I didn't take the time to track down. Anyways, it seems you are on the right track.

like image 58
Fiver Avatar answered Sep 21 '22 18:09

Fiver


Use the authenticate_header method on your authentication class.

Additionally that'll ensure your responses also have the right 401 Unauthorized status code set, instead of 403 Forbidden.

See here: http://django-rest-framework.org/api-guide/authentication.html#custom-authentication

like image 44
Tom Christie Avatar answered Sep 19 '22 18:09

Tom Christie