开发者

ajax request failing for csrf on some browsers

开发者 https://www.devze.com 2023-03-26 12:00 出处:网络
am using django and jquery for my application, I got to a point where I started using ajax but at first It was failing. Then, I found an article saying that I must somehow send off the csrf_token in m

am using django and jquery for my application, I got to a point where I started using ajax but at first It was failing. Then, I found an article saying that I must somehow send off the csrf_token in my post so I used the following script

$(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_开发者_如何转开发origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}

the script is getting the token from the cookie and including it in every ajax send. For some reason, the code is working perfectly in Safari but when I try using it with chrome or FF its failing.

I've already published the code into a temporary site www.mazban-staging.com/blog/ when page is loaded, there is a calendar on the right side. Click on next and see what happens, as I said only with Safari it works.

can anyone advice how i can solve this issue?

regards,


i think the problem here is that Ffx and chrome block reading the http cookie unlike safari.. having said that what you can do is stick in the token in an hidden field as follows

<input type="hidden" value="crypttoken" />

Now for very post back you send back this crypttoken and the cookie is sent anyways you compare the same and you should be safe.

This also avoids the use of Session or whatever you are using to store the crypttoken on the server side.

I am wondering hw you are able to read the cookie on Sadari

0

精彩评论

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