@@ -39,6 +39,34 @@ replaced instead of using ``CsrfMiddleware``.
39
39
(previous versions of Django did not provide these two components
40
40
of ``CsrfMiddleware`` as described above)
41
41
42
+ AJAX
43
+ ----
44
+
45
+ While the above method can be used with AJAX POST requests, it has some
46
+ inconveniences: you have to remember to get the CSRF token from the HTML
47
+ document and pass it in as POST data with every POST request. For this reason,
48
+ there is an alternative method: on each XMLHttpRequest, set a custom
49
+ `X-CSRFToken` header to the value of the CSRF token. This is often easier,
50
+ because many javascript frameworks provide hooks that allow headers to be set on
51
+ every request. In jQuery, you can use the ``beforeSend`` hook as follows:
52
+
53
+ .. code-block:: javascript
54
+
55
+ $.ajaxSetup({
56
+ beforeSend: function(xhr, settings) {
57
+ if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
58
+ // Only send the token to relative URLs i.e. locally.
59
+ xhr.setRequestHeader("X-CSRFToken",
60
+ $("#csrfmiddlewaretoken").val());
61
+ }
62
+ }
63
+ });
64
+
65
+ Adding this to a javascript file that is included on your site will ensure that
66
+ AJAX POST requests that are made via jQuery will not be caught by the CSRF
67
+ protection. This will only work if you remember to include a form on the page,
68
+ so that the input with id 'csrfmiddlewaretoken' will be found.
69
+
42
70
Exceptions
43
71
----------
44
72
@@ -61,10 +89,6 @@ disable the view protection mechanism (``CsrfViewMiddleware``) and the
61
89
response post-processing (``CsrfResponseMiddleware``) respectively.
62
90
They can be used individually if required.
63
91
64
- You don't have to worry about doing this for most AJAX views. Any
65
- request sent with "X-Requested-With: XMLHttpRequest" is automatically
66
- exempt. (See the next section.)
67
-
68
92
How it works
69
93
============
70
94
@@ -98,14 +122,6 @@ The Content-Type is checked before modifying the response, and only
98
122
pages that are served as 'text/html' or 'application/xml+xhtml'
99
123
are modified.
100
124
101
- The middleware tries to be smart about requests that come in via AJAX. Many
102
- JavaScript toolkits send an "X-Requested-With: XMLHttpRequest" HTTP header;
103
- these requests are detected and automatically *not* handled by this middleware.
104
- We can do this safely because, in the context of a browser, the header can only
105
- be added by using ``XMLHttpRequest``, and browsers already implement a
106
- same-domain policy for ``XMLHttpRequest``. (Note that this is not secure if you
107
- don't trust content within the same domain or subdomains.)
108
-
109
125
110
126
.. _9.1.1 Safe Methods, HTTP 1.1, RFC 2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
111
127
0 commit comments