日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

ajax中加上AntiForgeryToken防止CSRF攻击

發(fā)布時(shí)間:2024/9/20 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ajax中加上AntiForgeryToken防止CSRF攻击 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

經(jīng)常看到在項(xiàng)目中ajax post數(shù)據(jù)到服務(wù)器不加防偽標(biāo)記,造成CSRF攻擊

在Asp.net Mvc里加入防偽標(biāo)記很簡(jiǎn)單在表單中加入Html.AntiForgeryToken()即可。

Html.AntiForgeryToken()會(huì)生成一對(duì)加密的字符串,分別存放在Cookies 和?input 中。

我們?cè)赼jax post中也帶上AntiForgeryToken

@model WebApplication1.Controllers.Person @{ViewBag.Title = "Index"; }<h2>Index</h2> <form id="form1"><div class="form-horizontal"><h4>Persen</h4><hr />@Html.ValidationSummary(true, "", new { @class = "text-danger" })<div class="form-group">@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })</div></div><div class="form-group">@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })</div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="button" id="save" value="Create" class="btn btn-default" /></div></div></div></form> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> <script type="text/javascript">$(function () {//var token = $('[name=__RequestVerificationToken]');//獲取防偽標(biāo)記var token = $('@Html.AntiForgeryToken()').val();var headers = {};//防偽標(biāo)記放入headers//也可以將防偽標(biāo)記放入dataheaders["__RequestVerificationToken"] = token;$("#save").click(function () {$.ajax({type: 'POST',url: '/Home/Index',cache: false,headers: headers,data: { Name: "yangwen", Age: "1" },success: function (data) {alert(data)},error: function () {alert("Error")}});})}) </script>

放在cookies里面的加密字符串

控制器中代碼


using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Helpers; using System.Web.Mvc;namespace WebApplication1.Controllers{public class HomeController : Controller{public ActionResult Index(){return View();}[HttpPost][MyValidateAntiForgeryToken]public ActionResult Index(Person p){return Json(true, JsonRequestBehavior.AllowGet);}}public class Person{public string Name { get; set; }public int Age { get; set; }}public class MyValidateAntiForgeryToken : AuthorizeAttribute{public override void OnAuthorization(AuthorizationContext filterContext){var request = filterContext.HttpContext.Request;if (request.HttpMethod == WebRequestMethods.Http.Post){ if (request.IsAjaxRequest()){var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];var cookieValue = antiForgeryCookie != null? antiForgeryCookie.Value: null;//從cookies 和 Headers 中 驗(yàn)證防偽標(biāo)記//這里可以加try-catchAntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);}else{new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);}}}}}

這里注釋掉ajax中防偽標(biāo)記在請(qǐng)求

$("#save").click(function () {$.ajax({type: 'POST',url: '/Home/Index',cache: false,// headers: headers,data: { Name: "yangwen", Age: "1" },success: function (data) {alert(data)},error: function () {alert("Error")}});})

默認(rèn)返回500的狀態(tài)碼。

這里修改ajax中的防偽標(biāo)記

$(function () {//var token = $('[name=__RequestVerificationToken]');//獲取防偽標(biāo)記var token = $('@Html.AntiForgeryToken()').val();var headers = {};//防偽標(biāo)記放入headers//也可以將防偽標(biāo)記放入dataheaders["__RequestVerificationToken"] = token+11111111111111111111111111111111111;$("#save").click(function () {$.ajax({type: 'POST',url: '/Home/Index',cache: false,headers: headers,data: { Name: "yangwen", Age: "1" },success: function (data) {alert(data)},error: function () {alert("Error")}});})})

也是500的狀態(tài)碼。

總結(jié)

以上是生活随笔為你收集整理的ajax中加上AntiForgeryToken防止CSRF攻击的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。