Cross-Site Request Forgery in AJAX requests

You have learned Cross-Site Request Forgery in Chapter 2, Enhancing Your Blog with Advanced Features. With the CSRF protection active, Django checks for a CSRF token in all POST requests. When you submit forms, you can use the {% csrf_token %} template tag to send the token along with the form. However, it is a bit inconvenient for AJAX requests to pass the CSRF token as a POST data in with every POST request. Therefore, Django allows you to set a custom X-CSRFToken header in your AJAX requests with the value of the CSRF token. This allows you to set up jQuery or any other JavaScript library to automatically set the X-CSRFToken header in every request.

In order to include the token in all requests, you need to take the following steps:

  1. Retrieve the CSRF token from the csrftoken cookie, which is set if CSRF protection is active
  2. Send the token in the AJAX request using the X-CSRFToken header

You can find more information about CSRF protection and AJAX at https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax.

Edit the last code you included in your base.html template and make it look like the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script>
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$(document).ready(function(){
{% block domready %}
{% endblock %}
});
</script>

The preceding code is as follows:

  1. We load the JS Cookie plugin from a public CDN so that we can easily interact with cookies. JS Cookie is a lightweight JavaScript for handling cookies. You can learn more about it at https://github.com/js-cookie/js-cookie.
  2. We read the value of the csrftoken cookie with Cookies.get().
  1. We define the csrfSafeMethod() function to check whether an HTTP method is safe. Safe methods don't require CSRF protection—these are GET, HEAD, OPTIONS, and TRACE.
  2. We set up jQuery AJAX requests using $.ajaxSetup(). Before each AJAX request is performed, we check whether the request method is safe and the current request is not cross-domain. If the request is unsafe, we set the X-CSRFToken header with the value obtained from the cookie. This setup will apply to all AJAX requests performed with jQuery.

The CSRF token will be included in all AJAX requests that use unsafe HTTP methods, such as POST or PUT.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset