Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Django. Ajax. Is it wrong to send the csrf token like this?

I'm wondering if I'm doing it correctly and if it is safe. Usually I send the csrf token on an AJAX request using Jquery like this:

$.ajax({
       method: "POST",
       ...
       data: {...'csrfmiddlewaretoken': '{{csrf_token}}'},
       });

It works, but the documentation doesn't say anything about doing something like this. What is the difference between this and doing what the documentation recommends (getting the cookie and setting in on the header)?.

Upvotes: 2

Views: 507

Answers (2)

Oleksii M
Oleksii M

Reputation: 1518

Disadvantages of using context variable over header are:

  1. You should always include csrfmiddlewaretoken in data
  2. In general, you cannot store your JS code in separate file, you are restricted to store it in templates.

Django docs provide you with copy-paste js code, you can include in your scripts at project level and forget about csrfmiddlewaretoken

Upvotes: 1

Alasdair
Alasdair

Reputation: 308809

The advantage of reading the value from the cookie then setting the header, is that it is less repetitive. It also works if your ajax request is in a static javascript file (if it's not a Django template then you can't use {{ csrf_token }})

However, if you are happy adding the csrf token to the data of each ajax post request, that is fine, there is no problem doing it that way.

Upvotes: 1

Related Questions