确保每个控制器方法都有一个ValidateAntiForgeryToken属性?

Joe*_*Fan 16 security asp.net-mvc

是否有任何方法可以集中执行每个操作方法必须具有"ValidateAntiForgeryToken"属性?我认为必须通过扩展一个"路由"类来完成.

编辑:或者也许在应用程序启动时做一些反思?

edu*_*911 22

是.您可以通过创建自己的继承Mvc控制器的BaseController并重载OnAuthorization()来实现此目的.您希望在强制执行之前确保它是POST事件:

public abstract class MyBaseController : Controller
{
  protected override void OnAuthorization(AuthorizationContext filterContext)
  {
    //enforce anti-forgery stuff for HttpVerbs.Post
    if (String.Compare(filterContext.HttpContext.Request.HttpMethod,
          System.Net.WebRequestMethods.Http.Post, true) == 0)
    {
      var forgery = new ValidateAntiForgeryTokenAttribute();
      forgery.OnAuthorization(filterContext);
    }
    base.OnAuthorization(filterContext);
  }
}
Run Code Online (Sandbox Code Playgroud)

完成之后,请确保所有控制器都继承自此MyBaseController(或您所称的任何控制器).或者,如果您喜欢使用相同的代码,则可以在每个Controller上执行此操作.

  • 可以使用System.Net.WebRequestMethods.Http.Post而不是"post" (4认同)

Joh*_*ell 8

听起来你正试图阻止"哎呀我忘了设置那个"错误.如果是这样,我认为最好的地方是使用自定义ControllerActionInvoker.

基本上你想要做的就是阻止MVC甚至找不到没有AntiForgery令牌的动作:

public class MustHaveAntiForgeryActionInvoker : ControllerActionInvoker
{
    protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
    {
        var foundAction = base.FindAction(controllerContext, controllerDescriptor, actionName);

        if( foundAction.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), true ).Length == 0 )
            throw new InvalidOperationException("Can't find a secure action method to execute");

        return foundAction;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中,最好你的基本控制器:

ActionInvoker = new MustHaveAntiForgeryActionInvoker();
Run Code Online (Sandbox Code Playgroud)

只是想添加自定义Controller基类往往变得"厚",并且imo总是最好的做法,使用MVC的卓越扩展点来连接你需要的功能.

这是MVC大多数可扩展性点的一个很好的指南:http: //codeclimber.net.nz/archive/2009/04/08/13-asp.net-mvc-extensibility-points-you-have-to-know. ASPX


Gle*_*rde 7

好的,我刚刚将项目升级到MVC v2.0,如果您使用AuthorizeAttribute控制器操作,eduncan911的解决方案将不再起作用.有点难以弄清楚原因.

因此,故事中的罪魁祸首是MVC团队ViewContext.HttpContext.User.Identity.Name在该值中添加了该属性的使用RequestVerificationToken.

OnAuthorization在控制器操作上的任何过滤器之前执行基本控制器中的重写.因此,问题是尚未调用Authorize属性,因此ViewContext.HttpContext.User未设置.因此UserName是String.Empty,而用于验证的AntiForgeryToken包括真实用户名=失败.

我们现在用以下代码解决了它:

public abstract class MyBaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        //enforce anti-forgery stuff for HttpVerbs.Post
        if (String.Compare(filterContext.HttpContext.Request.HttpMethod, "post", true) == 0)
        {
            var authorize = new AuthorizeAttribute();
            authorize.OnAuthorization(filterContext);
            if (filterContext.Result != null) // Short circuit validation
                return;
            var forgery = new ValidateAntiForgeryTokenAttribute();
            forgery.OnAuthorization(filterContext);
        }
        base.OnAuthorization(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

一些对MVC代码库的引用:

ControllerActionInvoker#InvokeAuthorizationFilters()第283行.相同的短路. AntiForgeryData#GetUsername()第98行.新功能.