我们使用Ajax访问请求的时候,攻击者可能盗用了用户身份,以用户合法身份发送恶意请求。
具体预防措施,
1、在Html表单里面使用@Html.AntiForgeryToken(),这玩意会生成一对加密的字符串,分别存放在Cookies 和 input 中。
可以获取到,var token = $('@Html.AntiForgeryToken()').val();
2、在Controller中加入[ValidateAntiForgeryToken]过滤特性。
3、在JS中使用: $.ajaxAntiForgery才行,或者$.ajax中添加Header属性,或者在项目中引用<script src="@Url.Content("~/Content/js/jqueryToken-1.4.2.js")" type="text/javascript"></script>
var headers = {}; headers["__RequestVerificationToken"] = token; $.ajax({ type: 'POST', url: '/Home/Index', cache: false, headers: headers, data: { Name: "yangwen", Age: "1" }, success: function (data) { alert(data) }, error: function () { alert("Error") } });
或者封装一个Jquery方法:
(function ($) { $.getAntiForgeryToken = function (tokenWindow, appPath) { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. tokenWindow = tokenWindow && typeof tokenWindow === typeof window ? tokenWindow : window; appPath = appPath && typeof appPath === "string" ? "_" + appPath.toString() : ""; // The name attribute is either __RequestVerificationToken, // or __RequestVerificationToken_{appPath}. var tokenName = "__RequestVerificationToken" + appPath; var inputElements = tokenWindow.document.getElementsByTagName("input"); for (var i = 0; i < inputElements.length; i++) { var inputElement = inputElements[i]; if (inputElement.type === "hidden" && inputElement.name === tokenName) { return { name: tokenName, value: inputElement.value }; } } }; $.appendAntiForgeryToken = function (data, token) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } // Gets token from current window by default. token = token ? token : $.getAntiForgeryToken(); // $.getAntiForgeryToken(window). data = data ? data + "&" : ""; // If token exists, appends {token.name}={token.value} to data. return token ? data + encodeURIComponent(token.name) + "=" + encodeURIComponent(token.value) : data; }; // Wraps $.post(url, data, callback, type) for most common scenarios. $.postAntiForgery = function (url, data, callback, type) { return $.post(url, $.appendAntiForgeryToken(data), callback, type); }; // Wraps $.ajax(settings). $.ajaxAntiForgery = function (settings) { // Supports more options than $.ajax(): // settings.token, settings.tokenWindow, settings.appPath. var token = settings.token ? settings.token : $.getAntiForgeryToken(settings.tokenWindow, settings.appPath); settings.data = $.appendAntiForgeryToken(settings.data, token); return $.ajax(settings); }; })(jQuery);