How to protect against CSRF by default in ASP.NET MVC 4?

前端 未结 4 377
时光取名叫无心
时光取名叫无心 2021-01-30 14:38

Is there a way to ensure ASP.NET MVC 4 forms are protected against CSRF by default?

For instance, is there a way to have AntiForgeryToken automatically

4条回答
  •  余生分开走
    2021-01-30 15:14

    To add to osoviejo's excellent answer, the instructions below, from my recent blog post on CSRF, put his work together with the information in Phil's blog in one comprehensive answer.

    ASP.NET/MVC provides a mechanism for this: you can add to to a collection of filters on the global FilterProviders object. This allows you to target some controllers and not others, adding the needed security feature.

    First, we need to implement an IFilterProvider. Below, you can find Phil Haack's Conditional Filter Provider class. Begin by adding this class to your project.

    public class ConditionalFilterProvider : IFilterProvider
    {
        private readonly
          IEnumerable> _conditions;
    
        public ConditionalFilterProvider(
          IEnumerable> conditions)
        {
            _conditions = conditions;
        }
    
        public IEnumerable GetFilters(
            ControllerContext controllerContext,
            ActionDescriptor actionDescriptor)
        {
            return from condition in _conditions
                   select condition(controllerContext, actionDescriptor) into filter
                   where filter != null
                   select new Filter(filter, FilterScope.Global, null);
        }
    }
    

    Then, add code to Application_Start that adds a new ConditionalFilterProvider to the global FilterProviders collection that ensures that all POST controller methods will require the AntiForgeryToken.

    IEnumerable> conditions = 
        new Func[] {
        // Ensure all POST actions are automatically 
        // decorated with the ValidateAntiForgeryTokenAttribute.
    
        ( c, a ) => string.Equals( c.HttpContext.Request.HttpMethod, "POST",
        StringComparison.OrdinalIgnoreCase ) ?
        new ValidateAntiForgeryTokenAttribute() : null
    };
    
    var provider = new ConditionalFilterProvider(conditions);
    
    // This line adds the filter we created above
    FilterProviders.Providers.Add(provider);
    

    If you implement the two pieces of code above, your MVC application should require the AntiForgeryToken for every POST to the site. You can try it out on Phil Haack's CSRF example web site - once protected, the CSRF attack will throw System.Web.Mvc.HttpAntiForgeryException without having to add the [ValidateAntiForgeryToken] annotation. This rules out a whole host of "forgetful programmer" related vulnerabilities.

提交回复
热议问题