make sure each controller method has a ValidateAntiForgeryToken attribute?

前端 未结 4 1512
温柔的废话
温柔的废话 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:59

    Yes. You can do this by creating your own BaseController that inherits the Mvc Controller, and overloads the OnAuthorization(). You want to make sure it is a POST event before enforcing it:

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

    Once you have that, make sure all of your controllers inherit from this MyBaseController (or whatever you call it). Or you can do it on each Controller if you like with the same code.

提交回复
热议问题