How can I set the ValidateAntiForgeryToken globally

前端 未结 1 1096
青春惊慌失措
青春惊慌失措 2020-12-30 06:14

Security at first.

MVC best practices reccomend to add the [ValidateAntiForgeryToken] attribute to each [HttpPost] action.

How can

相关标签:
1条回答
  • 2020-12-30 07:09

    The follwing class allow to do this with a FilterProvider

    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        List<Filter> result = new List<Filter>();
    
        string incomingVerb = controllerContext.HttpContext.Request.HttpMethod;
    
        if (String.Equals(incomingVerb, "POST", StringComparison.OrdinalIgnoreCase))
        {
            result.Add(new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null));
        }
    
        return result;
    }
    

    To use the above class add this to the RegisterGlobalFilters method in global.asx file:

    ...    
    FilterProviders.Providers.Add(new AntiForgeryTokenFilterProvider ());
    ..
    

    Doing this, each [HttpPost] will check if the Html.AntiForgeryToken() is in the view.

    0 讨论(0)
提交回复
热议问题