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

來源:互聯網
上載者:User

經常看到在項目中ajax post資料到伺服器不加防偽標記,造成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);     }    }   }  } }

這裡注釋掉ajax中防偽標記在請求

$("#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的狀態代碼。

這裡修改ajax中的防偽標記

  $(function () { //var token = $('[name=__RequestVerificationToken]'); //擷取防偽標記 var token = $('@Html.AntiForgeryToken()').val(); var headers = {}; //防偽標記放入headers //也可以將防偽標記放入data headers["__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的狀態代碼。

以上內容就是本文的全部敘述,切記ajax中要帶上AntiForgeryToken防止CSRF攻擊,小夥伴們在使用過程發現有疑問,請給我留言,謝謝!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.