14

Security at first.

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

How can I enforce this rule in one unique point of the application?

Fabrizio
  • 511
  • 1
  • 4
  • 9

1 Answers1

18

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.

Fabrizio
  • 511
  • 1
  • 4
  • 9
  • 1
    Does your filter provider inherit from any base class? – Paul Jun 15 '11 at 03:00
  • 5
    The code will cause a list to be created for every request to the application. It can be improved by using yield: yield return new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null); – ShadowChaser Jun 30 '12 at 20:28
  • 2
    link to the full class for clarities sake: https://code.google.com/p/vnecoo/source/browse/trunk/Code/Oas2011/OAS/Helpers/AntiForgeryTokenFilterProvider.cs?r=148 – Jon Nov 07 '13 at 10:41