Opened 12 years ago
Closed 12 years ago
#19486 closed Bug (wontfix)
csrf_token tag is empty on Resolver404 error
Reported by: | SardarNL | Owned by: | nobody |
---|---|---|---|
Component: | Core (Other) | Version: | 1.4 |
Severity: | Normal | Keywords: | csrf |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
The tag {% csrf_token %} prints context.csrf_token, which is set by default django.core.context_processors.csrf, which uses django.middleware.csrf.get_token(), which looks in request.META['CSRF_COOKIE']
, which is set by CsrfViewMiddleware.process_view(). So if process_view() isn't called, then there will be no META['CSRF_COOKIE']
, then {% csrf_token %} would print nothing.
Lets look now at django.core.handlers.BaseHandler.get_response(). It first calls all process_request(), then resolves the view and *then* calls all process_view(). So, if none of your URL patterns match, then your CsrfViewMiddleware.process_view() will not be called. Resolver404 exception is http.Http404, so if no view is found, the handler will use resolver.resolve404() view to serve 404 page.
The problem: 404 page uses {% csrf_token %} to render a POST form to search view. It works if URL is matched by a view, but the view itself raises Http404. It doesn't work if URL is not matched by any pattern.
Solution:
1) refactor CsrfViewMiddleware.process_view(), move setting
request.META['CSRF_COOKIE']
to a separate _method()
2) call this method for resolver.resolve404() view or in get_token()
Possible problems: browser may ignore cookies set by 404 page.
Workaround: search page is using csrf_exempt at this moment.
Severity: minor