某程序员大神God在某在线银行Online Bank给他的朋友Friend转帐。javascript
转帐后,出于好奇,大神God查看了网站的源文件,以及捕获到转帐的请求。html
大神God发现,这个网站没有作防止CSRF的措施,并且他本身也有一个有必定访问量的网站,因而,他计划在本身的网站上内嵌一个隐藏的Iframe伪造请求(每10s发送一次),来等待鱼儿Fish上钩,给本身转帐。java
网站源码:git
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title></title> </head> <body> <div> 我是一个内容丰富的网站,你不会关闭我! </div> <iframe name="frame" src="invalid.html" sandbox="allow-same-origin allow-scripts allow-forms" style="display: none; width: 800px; height: 1000px;"> </iframe> <script type="text/javascript"> setTimeout("self.location.reload();", 10000); </script> </body> </html>
伪造请求源码:程序员
<html> <head> <title></title> </head> <body> <form id="theForm" action="http://localhost:22699/Home/Transfer" method="post"> <input class="form-control" id="TargetUser" name="TargetUser" placeholder="用户名" type="text" value="God" /> <input class="form-control" id="Amount" name="Amount" placeholder="转帐金额" type="text" value="100" /> </form> <script type="text/javascript"> document.getElementById('theForm').submit(); </script> </body> </html>
鱼儿Fish打开了大神God的网站,在上面浏览丰富多彩的内容。此时伪造请求的结果是这样的(为了演示效果,去掉了隐藏):github
由于鱼儿Fish没有登录,因此,伪造请求一直没法执行,一直跳转回登陆页面。web
而后鱼儿Fish想起了要登陆在线银行Online Bank查询内容,因而他登陆了Online Bank。ajax
此时伪造请求的结果是这样的(为了演示效果,去掉了隐藏):数据库
鱼儿Fish每10秒会给大神God转帐100元。json
CSRF能成功是由于同一个浏览器会共享Cookies,也就是说,经过权限认证和验证是没法防止CSRF的。那么应该怎样防止CSRF呢?其实防止CSRF的方法很简单,只要确保请求是本身的站点发出的就能够了。那怎么确保请求是发自于本身的站点呢?ASP.NET以Token的形式来判断请求。
咱们须要在咱们的页面生成一个Token,发请求的时候把Token带上。处理请求的时候须要验证Cookies+Token。
此时伪造请求的结果是这样的(为了演示效果,去掉了隐藏):
若是个人请求不是经过Form提交,而是经过Ajax来提交,会怎样呢?结果是验证不经过。
为何会这样子?咱们回头看看加了@Html.AntiForgeryToken()后页面和请求的变化。
1. 页面多了一个隐藏域,name为__RequestVerificationToken。
2. 请求中也多了一个字段__RequestVerificationToken。
原来要加这么个字段,我也加一个不就能够了!
啊!为何仍是不行...逼我放大招,研究源码去!
噢!原来token要从Form里面取。可是ajax中,Form里面并无东西。那token怎么办呢?我把token放到碗里,不对,是放到header里。
js代码:
$(function () { var token = $('@Html.AntiForgeryToken()').val(); $('#btnSubmit').click(function () { var targetUser = $('#TargetUser').val(); var amount = $('#Amount').val(); var data = { 'targetUser': targetUser, 'amount': amount }; return $.ajax({ url: '@Url.Action("Transfer2", "Home")', type: 'POST', data: JSON.stringify(data), contentType: 'application/json', dataType: 'json', traditional: 'true', beforeSend: function (xhr) { xhr.setRequestHeader('__RequestVerificationToken', token); }, success:function() { window.location = '@Url.Action("Index", "Home")'; } }); }); });
在服务端,参考ValidateAntiForgeryTokenAttribute,编写一个AjaxValidateAntiForgeryTokenAttribute:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AjaxValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } var request = filterContext.HttpContext.Request; var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null; var formToken = request.Headers["__RequestVerificationToken"]; AntiForgery.Validate(cookieValue, formToken); } }
而后调用时把ValidateAntiForgeryToken替换成AjaxValidateAntiForgeryToken。
大功告成,好有成就感!
若是全部的操做请求都要加一个ValidateAntiForgeryToken或者AjaxValidateAntiForgeryToken,不是挺麻烦吗?能够在某个地方统一处理吗?答案是阔仪的。
ValidateAntiForgeryTokenAttribute继承IAuthorizationFilter,那就在AuthorizeAttribute里作统一处理吧。
ExtendedAuthorizeAttribute:
public class ExtendedAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { PreventCsrf(filterContext); base.OnAuthorization(filterContext); GenerateUserContext(filterContext); } /// <summary> /// http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages /// </summary> private static void PreventCsrf(AuthorizationContext filterContext) { var request = filterContext.HttpContext.Request; if (request.HttpMethod.ToUpper() != "POST") { return; } var allowAnonymous = HasAttribute(filterContext, typeof(AllowAnonymousAttribute)); if (allowAnonymous) { return; } var bypass = HasAttribute(filterContext, typeof(BypassCsrfValidationAttribute)); if (bypass) { return; } if (filterContext.HttpContext.Request.IsAjaxRequest()) { var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null; var formToken = request.Headers["__RequestVerificationToken"]; AntiForgery.Validate(cookieValue, formToken); } else { AntiForgery.Validate(); } } private static bool HasAttribute(AuthorizationContext filterContext, Type attributeType) { return filterContext.ActionDescriptor.IsDefined(attributeType, true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(attributeType, true); } private static void GenerateUserContext(AuthorizationContext filterContext) { var formsIdentity = filterContext.HttpContext.User.Identity as FormsIdentity; if (formsIdentity == null || string.IsNullOrWhiteSpace(formsIdentity.Name)) { UserContext.Current = null; return; } UserContext.Current = new WebUserContext(formsIdentity.Name); } }
而后在FilterConfig注册一下。
FAQ:
1. BypassCsrfValidationAttribute是什么鬼?不是有个AllowAnonymousAttribute吗?
若是有些操做你不须要作CSRF的处理,好比附件上传,你能够在对应的Controller或Action上添加BypassCsrfValidationAttribute。
AllowAnonymousAttribute不只会绕过CSRF的处理,还会绕过认证和验证。BypassCsrfValidationAttribute绕过CSRF但不绕过认证和验证,
也就是BypassCsrfValidationAttribute做用于那些登陆或受权后的Action。
2. 为何只处理POST请求?
我开发的时候有一个原则,查询都用GET,操做用POST,而对于查询的请求没有必要作CSRF的处理。你们能够按本身的须要去安排!
3. 我作了全局处理,而后还在Controller或Action上加了ValidateAntiForgeryToken或者AjaxValidateAntiForgeryToken,会冲突吗?
不会冲突,只是验证会作两次。
为了方便使用,我没有使用任何数据库,而是用了一个文件来存储数据。代码下载后能够直接运行,无需配置。