MVC防止xss攻击 ——Html.AntiForgeryToken的AJAX提交
1、在Html表單里面使用了@Html.AntiForgeryToken()就可以阻止CSRF攻擊。
2、相應的我們要在Controller中也要加入[ValidateAntiForgeryToken]過濾特性。該特性表示檢測服務器請求是否被篡改。注意:該特性只能用于post請求,get請求無效。
3、至于JS,我們的項目中引用的是<script src="@Url.Content("~/Content/js/jqueryToken-1.4.2.js")" type="text/JavaScript"></script>
在JS時要使用: $.ajaxAntiForgery才行,
如:
?$.ajaxAntiForgery({
??????????? type: "post",
??????????? data: { GroupName: $("#GroupName").val(), GroupPhones: $("#GroupPhones").val() },
??????????? dataType: "json",
??????????? url: "/Event/Mass/AddGroup",
??????????? success: function (data) {
??????????????? if (data) {
??????????????????? alert("添加成功 ");
??????????????????? $.unblockUI();
??????????????? }
??????????????? else {
??????????????????? alert("添加失敗 ");
??????????????? }
???????? }
?})
注:對數據進行增刪改時要防止csrf攻擊!
另外一種方式
?
public class HomeController : Controller {public ActionResult Index(){return View();}[HttpPost][ValidateAntiForgeryToken]public ActionResult Index(string someValue){return Json(new { someValue = someValue });} }?
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" })) {@Html.AntiForgeryToken() }<div id="myDiv" data-url="@Url.Action("Index", "Home")">Click me to send an AJAX request to a controller actiondecorated with the [ValidateAntiForgeryToken] attribute </div><script type="text/javascript">$('#myDiv').submit(function () {var form = $('#__AjaxAntiForgeryForm');var token = $('input[name="__RequestVerificationToken"]', form).val();$.ajax({url: $(this).data('url'),type: 'POST',data: { __RequestVerificationToken: token, someValue: 'some value' },success: function (result) {alert(result.someValue);}});return false;}); </script>?
轉載于:https://www.cnblogs.com/l1pe1/p/6030841.html
總結
以上是生活随笔為你收集整理的MVC防止xss攻击 ——Html.AntiForgeryToken的AJAX提交的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UIAlertAction添加输入框
- 下一篇: ztree插件的使用