make sure each controller method has a ValidateAntiForgeryToken attribute?

前端 未结 4 1523
温柔的废话
温柔的废话 2020-12-24 04:23

Is there any way to centralize enforcement that every action method must have a \"ValidateAntiForgeryToken\" attribute? I\'m thinking it would have to be done by extending

4条回答
  •  佛祖请我去吃肉
    2020-12-24 04:53

    Sounds like you're trying to prevent "oops I forgot to set that" bugs. If so I think the best place to do this is with a custom ControllerActionInvoker.

    Essentially what you want to do is stop MVC from even finding an action without a AntiForgery token:

    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;
        }
    }
    

    Then in your controller, preferably your base controller:

    ActionInvoker = new MustHaveAntiForgeryActionInvoker();
    

    Just wanted to add that custom Controller base classes tend to get "thick" and imo its always best practice to use MVC's brilliant extensibility points to hook in the features you need where they belong.

    Here is a good guide of most of MVC's extensibility points: http://codeclimber.net.nz/archive/2009/04/08/13-asp.net-mvc-extensibility-points-you-have-to-know.aspx

提交回复
热议问题