0

I have a problem/bug found? in AJAX with CSRF. I don't use {% csrf_token %} at all. I use only AJAX forms so - there is no cookie set for csrf. In taht case - enter link description here is useless :( I can use get_token to generate it, but I have to put it in all my sites so it has no sense.

How can I make that cookie without using csrf tag?

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
tunarob
  • 2,768
  • 4
  • 31
  • 48

4 Answers4

1

Any random 32-digit alphanumeric string will work as the token. Simply save it in a cookie named "csrftoken", and then submit it with your post.

This will auto generate a token or re-use an existing one. It will handle all form submits on the page. If you have off-site forms you'll need to make sure they don't run this code.

<script>
$(document).on('submit', 'form[method=post]', function(){
  if(!document.cookie.match('csrftoken=([a-zA-Z0-9]{32})')){
    for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)
    document.cookie = 'csrftoken=' + c + '; path=/'
  }
  if(!this.csrfmiddlewaretoken) $(this).append('<input type="hidden" name="csrfmiddlewaretoken">')
  $(this.csrfmiddlewaretoken).val(document.cookie.match('csrftoken=([a-zA-Z0-9]{32})')[1])
})
</script>

requires jQuery 1.7+

Collin Anderson
  • 14,787
  • 6
  • 68
  • 57
0

If you imprint csrf token into some JS variable on server side, then later you can send custom HTTP header that will be recognized by Django

X-CSRFToken: {{ csrf_token }}}

also see that Q&A: Django CSRF failure on ajax post requests on Opera only

Example of working request:

POST /main/uploadpage/ HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Content-Length: 505853
Origin: http://127.0.0.1:8000
X-File-Name: Screen Shot 2013-05-12 at 5.13.34 PM (2).png
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
Content-Type: image/png
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
X-CSRFToken: 1kCcyDzpHIxicSzCqvuXUMbpGaXvFpCZ
Accept: */*
Referer: http://127.0.0.1:8000/main/uploadpage/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Community
  • 1
  • 1
Alfishe
  • 3,430
  • 1
  • 25
  • 19
0

You can use the csrf_exempt decorator on your view

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt

Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
-1

have u consider disabling CSRF at all?

to do that just remove the middleware : 'django.middleware.csrf.CsrfViewMiddleware',

Arthur Neves
  • 11,840
  • 8
  • 60
  • 73
  • 1
    That is a really bad idea. The CSRF protection isn't there just to annoy you, it serves a purpose. – Tom Nov 09 '11 at 16:52
  • as a matter of fact,it depends of the situation you have! for general rule dont disable CSRF, but you never know! – Arthur Neves Nov 09 '11 at 16:57