国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > AJAX > 正文

切記ajax中要帶上AntiForgeryToken防止CSRF攻擊

2024-09-01 08:28:19
字體:
供稿:網(wǎng)友

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

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

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

我們在ajax 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]');  //獲取防偽標記  var token = $('@Html.AntiForgeryToken()').val();  var headers = {};  //防偽標記放入headers  //也可以將防偽標記放入data  headers["__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 中 驗證防偽標記     //這里可以加try-catch     AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);     }    else     {     new ValidateAntiForgeryTokenAttribute()      .OnAuthorization(filterContext);     }    }   }  } }            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 莫力| 崇州市| 沙坪坝区| 青冈县| 连平县| 贵阳市| 宜春市| 革吉县| 霍山县| 遂溪县| 贵定县| 马关县| 萨迦县| 武汉市| 郎溪县| 通城县| 宁海县| 永定县| 宕昌县| 澄迈县| 开原市| 普兰县| 闵行区| 酒泉市| 明光市| 蒲江县| 福泉市| 炎陵县| 衡水市| 廊坊市| 台安县| 招远市| 永新县| 巴彦县| 搜索| 阳江市| 仁怀市| 德格县| 安新县| 额尔古纳市| 兴义市|