From 3fe5d0128b86438b38c5a4a27371aa7fdf91cb3d Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Thu, 12 Dec 2019 07:34:03 -0800 Subject: [PATCH] Rewrote CSRF JavaScript example without jQuery. --- docs/ref/csrf.txt | 36 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/docs/ref/csrf.txt b/docs/ref/csrf.txt index 94bf447aab..72277415af 100644 --- a/docs/ref/csrf.txt +++ b/docs/ref/csrf.txt @@ -137,39 +137,29 @@ and read the token from the DOM with JavaScript: {% csrf_token %} Setting the token on the AJAX request ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Finally, you'll have to actually set the header on your AJAX request, while -protecting the CSRF token from being sent to other domains using -`settings.crossDomain `_ in jQuery 1.5.1 -and newer: +Finally, you'll need to set the header on your AJAX request. Using the +`fetch()`_ API: .. code-block:: javascript - 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); - } - } + var request = new Request( + /* URL */, + {headers: {'X-CSRFToken': csrftoken}} + ); + fetch(request, { + method: 'POST', + mode: 'same-origin' // Do not send CSRF token to another domain. + }).then(function(response) { + // ... }); -If you're using AngularJS 1.1.3 and newer, it's sufficient to configure the -``$http`` provider with the cookie and header names: - -.. code-block:: javascript - - $httpProvider.defaults.xsrfCookieName = 'csrftoken'; - $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; +.. _fetch(): https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch Using CSRF in Jinja2 templates ------------------------------