所以这是我的问题:如何为Web API 2 Web服务的AJAX调用实现CSRF并对其进行验证?如果客户端创建CSRF令牌:
// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
并且AJAX在头部中发送它:
$.ajax({
type: "POST",
crossDomain: true,
url: "http://dev-blahblah/newWS/PostData",
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
xhrObj.setRequestHeader("Content-Type", "application/json");
},
data: {
theID: "2135648792",
empImg: "false"
},
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
}
});
现在这一切都很好,但真正的问题是: How does the server side know its a legit CSRF Token 如果它从来不知道它是什么(因为它是创建客户端)?
对我来说,这似乎是浪费时间,如果服务器端永远不知道在客户端创建了什么,并且实际上只查看是否在标头中发送了令牌 . 当将信息传递给服务器时,有人只能在那里注入一个随机令牌而服务器不会很好,因为它不知道令牌实际应该是什么?
所以尽管如此,一个例子(在流程视图中)看起来像这样:
-Web page loads up
|--Button is clicked to fire off AJAX req.
|--On the fly a token is created for the header.
|--Header is sent to the server as a check to see if one is there.
|--Regardless what the token value is, if the server sees it then its fine and continues.
所以,也许我正在以不正确的方式看待这一点,但我只是不认为这是一种安全的方式,看看是否有人想要破解网络服务 .