主頁 > 知識庫 > 切記ajax中要帶上AntiForgeryToken防止CSRF攻擊

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

熱門標簽:青海醫(yī)療智能外呼系統(tǒng)怎么樣 目標三維地圖標注 百靈鳥 徐州電銷卡外呼系統(tǒng)供應商 襄陽外呼系統(tǒng)接口 科智聯(lián)智能電銷機器人 上海浦東百度地圖標注中心注冊 外呼系統(tǒng)獲取客戶手機號 老虎郵局地圖標注點

經??吹皆陧椖恐衋jax post數(shù)據到服務器不加防偽標記,造成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的狀態(tài)碼。

這里修改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的狀態(tài)碼。

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

您可能感興趣的文章:
  • PHP實現(xiàn)登陸表單提交CSRF及驗證碼
  • Yii框架防止sql注入,xss攻擊與csrf攻擊的方法
  • 啟用Csrf后POST數(shù)據時出現(xiàn)的400錯誤
  • PHP開發(fā)中常見的安全問題詳解和解決方法(如Sql注入、CSRF、Xss、CC等)
  • PHP開發(fā)中csrf攻擊的簡單演示和防范

標簽:股票 揭陽 佛山 咸寧 荊州 商洛 辛集 紅河

巨人網絡通訊聲明:本文標題《切記ajax中要帶上AntiForgeryToken防止CSRF攻擊》,本文關鍵詞  切記,ajax,中,要,帶上,AntiForgeryToken,;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《切記ajax中要帶上AntiForgeryToken防止CSRF攻擊》相關的同類信息!
  • 本頁收集關于切記ajax中要帶上AntiForgeryToken防止CSRF攻擊的相關信息資訊供網民參考!
  • 推薦文章