Django does not send csrf token after clearing browser cookies

In a normal situation, django will send the csrf token through a cookie, which will later be used by the post ajax method. However, when I clear cookies in the browser (Chrome or Firefox), the csrf token is no longer sent to the browser, the session ID is still sent, but there is no csrf token. Does anyone know what is going wrong?

I solved this problem by adding {% csrf_token%} to my template and the SET-COOKIE header will appear along with this page request. it turns out that you have to put {% csrf-token%} in the template so that the server sends the token through the SET-COOKIE header

+4
source share
3 answers

Take a look at django/middleware/csrf.py , which CsrfViewMiddleware class. As you can see in def process_response(self, request, response) , there are three conditions that prevent the setting of cookies:

 def process_response(self, request, response): if getattr(response, 'csrf_processing_done', False): return response # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was # never called, probaby because a request middleware returned a response # (for example, contrib.auth redirecting to a login page). if request.META.get("CSRF_COOKIE") is None: return response if not request.META.get("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it already set, so we renew # the expiry timer. response.set_cookie(settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE ) # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',)) response.csrf_processing_done = True return response 

Check which one applies to you.

+3
source

I had the same problem. After debugging with the django source, the reason is this:

If your view does not display a template containing the csrf_token template tag, Django may not set the CSRF token cookie.

Two solutions:

  • Add {% csrf_token %} to your template
  • Use the @ensure_csrf_cookie decorator for your view

For more information, you can contact django doc .

+3
source

In most cases, the problem caused by the second check mentioned in the previous answer

 if not request.META.get("CSRF_COOKIE_USED", False): return response 

This can be resolved using the @ provide_csrf_cookie decorator for submission. If used, the check is transmitted and the cookie is set / updated each time the view is viewed.

See also the related topic: Using ajax request in Django without form element

0
source

All Articles