记录一下自己在MVC项目中如何防CSRF攻击,直接上代码

1.前端的处理:

 

2.后台 

 1.)添加过滤器,哪里用放哪里

2.)需要验证的方法上直接添加过滤器即可

大功告成

以下为过滤器代码块

/// <summary>
/// ajax中加上AntiForgeryToken防止CSRF攻击
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyValidateAntiForgeryToken : AuthorizeAttribute
{
private readonly bool _ignore;
/// <summary>
/// 防伪安全属性
/// </summary>
/// <param name="ignore">是否忽略安全验证</param>
public MyValidateAntiForgeryToken(bool ignore = false)
{
this._ignore = ignore;
}

public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("filterContext");

if (_ignore)
return;

if (filterContext.IsChildAction)
return;

///只处理POST请求
if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
return;

var request = filterContext.HttpContext.Request;
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null;
AntiForgery.Validate(cookieValue, request.Form["__RequestVerificationToken"]); //从cookies 和 Form中验证防伪标记 
}
}

posted @ 2019-11-01 13:36  代码沉思者  阅读(239)  评论(0编辑  收藏  举报