简体   繁体   中英

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?

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.

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

Your solution is quite correct, in my case I found it more appropiate to add the header and then call the method on the super instance, to maintain default behaviour:

class BaseView(APIView):
  def handle_exception(self, exc):
     if isinstance(exc, MYEXCEPTION):
        self.headers['WWW-Authenticate'] = "Token"
        return super().handle_exception(excepto)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM