Search code examples
djangosessioncsrfdjango-csrf

django's forbidden(403) response when session is expired, how to change it to unauthorized(401)


I am trying to upload a file in an application. I empty my browsing data or somehow end my session and then I hit upload. I select a file from my filesystem and I get a forbidden (403) error from Django's server. csrf.py's code get executed.

if not constant_time_compare(request_csrf_token, csrf_token):
                logger.warning('Forbidden (%s): %s',
                               REASON_BAD_TOKEN, request.path,
                    extra={
                        'status_code': 403,
                        'request': request,
                    }
                )
                return self._reject(request, REASON_BAD_TOKEN)

Now, that I dont want to change Django's code, how do I present 401 to the user and not 403. I dont want to capture 403 from server and change it to 401 in my Javascript. Any other solutions?? Thanks


Solution

  • The CSRF_FAILURE_VIEW setting allows you to write your own view for CSRF failures. You could write one that returns HTTP status 401.