前言
CSRF(Cross-site request forgery跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。本文使用ASP.NET MVC提供的AntiForgery进行安全验证
应用
一、自定义FilterAttribute过滤器
1 /// <summary> 2 /// 响应返回值 3 /// </summary> 4 public class TActionResult 5 { 6 /// <summary> 7 /// 创建一个返回值 8 /// </summary> 9 /// <param name="content">返回值</param> 10 /// <returns></returns> 11 public static ActionResult CreateResult(string content) 12 { 13 var contentResult = new ContentResult 14 { 15 16 Content = content, 17 ContentEncoding = Encoding.UTF8 18 }; 19 return contentResult; 20 } 21 }
1 public class TValidateAntiForgeryTokenAttribute : AuthorizeAttribute 2 { 3 public override void OnAuthorization(AuthorizationContext filterContext) 4 { 5 try 6 { 7 var request = filterContext.HttpContext.Request; 8 if (request.HttpMethod == WebRequestMethods.Http.Post) 9 { 10 if (request.IsAjaxRequest()) 11 { 12 var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; 13 var cookieValue = antiForgeryCookie != null 14 ? antiForgeryCookie.Value 15 : null; 16 //从cookies 和 Headers 中 验证防伪标记 17 //获取token 18 var token = request.Headers["__RequestVerificationToken"]; 19 //验证token 20 AntiForgery.Validate(cookieValue, token); 21 } 22 else 23 { 24 new ValidateAntiForgeryTokenAttribute() 25 .OnAuthorization(filterContext); 26 } 27 } 28 } 29 catch 30 { 31 filterContext.Result = TActionResult.CreateResult("无法验证Token!"); 32 } 33 } 34 }
二、视图
@Html.AntiForgeryToken()
三、HomeController
[TValidateAntiForgeryToken] public string Test() { return "Token验证通过!"; }
四、Jquery使用Ajax发请求
1. 设置全局请求头header
1 $.ajaxSetup({ 2 beforeSend: function (xhr) { 3 //可以设置自定义标头 4 xhr.setRequestHeader('__RequestVerificationToken', $("input[name=__RequestVerificationToken][type=hidden]").val()); 5 6 } 7 })
2.ajax请求
$.post("/home/test",function(msg) { alert(msg); })
五、备注:
1.如果Action上设置缓存,那么视图将不会再次调用@Html.AntiForgeryToken()生成新的,ajax请求还是携带上一次生成的token