Home > Mobile >  How to pass CSRF token manually for POST requests in ajax Django
How to pass CSRF token manually for POST requests in ajax Django

Time:09-21

We have a Django app which works as an iframe and it works fine in Safari and Chrome Browsers but in Safari it is blocking all the cookies and sessions that causes all the post request to be forbidden due to no CSRF Cookie. So is there any way we can pass this CSRF cookie along with headers using AJAX post.

CodePudding user response:

You can try to add the following to your ajax post

data['csrfmiddlewaretoken'] = jQuery("[name=csrfmiddlewaretoken]").val()

where data is the data you want to send to the server. For this to work you need to have the {% csrf_token %} somewhere on your website, otherwise jQuery can't find the tokens value.

CodePudding user response:

You can pass the csrf token from the View. You can grab it in one of these two ways (these I have tested personally and I'm sure they work):

  1. csrf_token = self.request.COOKIES.get('csrftoken')
  2. The second option tends to be more solid. I don't remember exactly what particular edge case it was but it worked once where the first solution proposed here failed.
# import
from django.middleware.csrf import get_token

# in the view
csrf_token = get_token(request)

Once you have grabbed the token you have to pass it to the template in whatever way you want. Let's assumet that you just add it to the context variable like this:

context['csrf_token'] = csrf_token

Great, now in the template you have to send it together with each request. In my experience you only need to do this with POST requests. The way to send it is by including it in the headers:

let response = await fetch('/my/api/url', {
    method: 'POST',
    body: JSON.stringify({
        'field1: 'value1',
        ...
    }),
    headers: {
        'X-CSRFToken': "{{ csrf_token }}",
        'Content-type': 'application/json'
    }
}).then(...

  • Related