Pregunta

  • I have a page that can be viewed authenticated or not.
  • This page contains form (with its CSRF token)
  • The form requires authentication to be taken into account
  • I manage the authentication check by ajax (on form submit)
  • If the user is not authenticated, he can do it from a new window (with a link)
  • Once authenticated, the user can close the new window and resubmit the form

In that case, Django tells me that my CRSF token is not valid anymore

CSRF token missing or incorrect

I imagine that's because the session_id has changed or something like that.

Is my assertion correct ?
How could I allow the user to resubmit the form without having to reload the page ?

¿Fue útil?

Solución

While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request.

You need to send the CSRF token through an AJAX call:

$.ajaxSetup({ 
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});

Here is reference link, https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/#ajax

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top