博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
记得ajax中要带上AntiForgeryToken防止CSRF攻击
阅读量:6939 次
发布时间:2019-06-27

本文共 4258 字,大约阅读时间需要 14 分钟。

经常看到在项目中ajax post数据到服务器不加防伪标记,造成CSRF攻击

在Asp.net Mvc里加入防伪标记很简单在表单中加入Html.AntiForgeryToken()即可。

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

我们在ajax post中也带上AntiForgeryToken

 

@model WebApplication1.Controllers.Person@{    ViewBag.Title = "Index";}

Index

Persen


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })

放在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的状态码。

转载地址:http://gnfnl.baihongyu.com/

你可能感兴趣的文章
open***负载均衡高可用多种方案实战讲解01(老男孩主讲)
查看>>
SQL Server 2012笔记分享-12:理解备份与恢复新特性
查看>>
FAQ:configuration manager未找到站点来管理此客户端
查看>>
TiDB VS MariaDB10.1.19 Enterprise性能压测
查看>>
百度云同步盘网络异常【1】解决办法(续)
查看>>
谁动了我的文件?
查看>>
京东刘强东的3次大抉择
查看>>
手机多图传输神器-快传正式版抢先评测
查看>>
分享三种简单的推广渠道,玩转引流精准粉
查看>>
U2L蔚然成风,曙光为什么能抢了VMware的风头?
查看>>
MySQL基础备忘(2)之视图
查看>>
MapGuide OpenSource 2.2 安装中的数字签名错误
查看>>
ubuntu分区
查看>>
艾伟_转载:学习 ASP.NET MVC (第五回)理论篇
查看>>
Amazon AWS云管理平台技术内幕,互联网营销
查看>>
【评论】GNU/Linux下有多少是GNU的?
查看>>
IE漏洞致数百万用户中招 快用瑞星卡卡打补丁
查看>>
瑞星义卖活动圆满结束 感谢用户积极参与
查看>>
【Oracle】SQL学习笔记1---基本概念及SELECT语句及提取和排序数据
查看>>
大流量网站的底层系统架构
查看>>