开发者

Django: CSRF with AJAX

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开发者_如何学JAVA 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?


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+


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


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


have u consider disabling CSRF at all?

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜