简体   繁体   English

如何在ASP.NET MVC 4中默认防止CSRF?

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

Is there a way to ensure ASP.NET MVC 4 forms are protected against CSRF by default? 有没有办法确保默认情况下ASP.NET MVC 4表单受CSRF保护?

For instance, is there a way to have AntiForgeryToken automatically applied to all forms in both views and controller actions? 例如,有没有办法让AntiForgeryToken 自动应用于视图和控制器操作中的所有表单?

Background on this question: Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC's AntiForgeryToken() helper and Anatomy of a Cross-site Request Forgery Attack . 关于这个问题的背景: 使用ASP.NET MVC的AntiForgeryToken()帮助程序跨站点请求伪造攻击剖析来 防止跨站点请求伪造(CSRF)

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. 为了增加osoviejo的优秀答案,下面的说明,从我最近关于CSRF的博客文章中 ,将他的工作与Phil博客中的信息放在一个综合答案中。

ASP.NET/MVC provides a mechanism for this: you can add to to a collection of filters on the global FilterProviders object. ASP.NET / MVC为此提供了一种机制:您可以添加到全局FilterProviders对象上的过滤器集合。 This allows you to target some controllers and not others, adding the needed security feature. 这允许您针对某些控制器而不是其他控制器,添加所需的安全功能。

First, we need to implement an IFilterProvider. 首先,我们需要实现一个IFilterProvider。 Below, you can find Phil Haack's Conditional Filter Provider class. 下面,您可以找到Phil Haack的条件过滤器提供程序类。 Begin by adding this class to your project. 首先将此类添加到项目中。

public class ConditionalFilterProvider : IFilterProvider
{
    private readonly
      IEnumerable<Func<ControllerContext, ActionDescriptor, object>> _conditions;

    public ConditionalFilterProvider(
      IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions)
    {
        _conditions = conditions;
    }

    public IEnumerable<Filter> 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. 然后,向Application_Start添加代码,将新的ConditionalFilterProvider添加到全局FilterProviders集合,以确保所有POST控制器方法都需要AntiForgeryToken。

IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions = 
    new Func<ControllerContext, ActionDescriptor, object>[] {
    // 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. 如果您实现上面的两段代码,您的MVC应用程序应该为站点的每个 POST都要求AntiForgeryToken。 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. 您可以在Phil Haack的CSRF示例网站上进行尝试 - 一旦受到保护,CSRF攻击将抛出System.Web.Mvc.HttpAntiForgeryException而无需添加[ValidateAntiForgeryToken]注释。 This rules out a whole host of "forgetful programmer" related vulnerabilities. 这排除了一大堆“健忘的程序员”相关漏洞。

You can use a filter provider with a condition that the filter ValidateAntiForgeryTokenAttribute() be applied whenever HttpContext.Request.HttpMethod == "POST". 您可以使用过滤器提供程序,条件是每当HttpContext.Request.HttpMethod ==“POST”时应用过滤器ValidateAntiForgeryTokenAttribute()。

I essentially followed the generic approach described by Phil Haack , and added the appropriate condition: 我基本上遵循Phil Haack描述的通用方法,并添加了适当的条件:

// Ensure all POST actions are automatically decorated with the ValidateAntiForgeryTokenAttribute.
( c, a ) => string.Equals( c.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase ) ?
 new ValidateAntiForgeryTokenAttribute() : null

I have used FXCop to write two code analysis rules one that require that a HttpMethod attribute is applied to all controller actions and a second that requires any action that has a HttpPost attribute must also have a RequiresAntiForgeryToken attribute. 我已经使用FXCop编写了两个代码分析规则,其中一个需要将HttpMethod属性应用于所有控制器操作,另一个需要具有HttpPost属性的任何操作也必须具有RequiresAntiForgeryToken属性。

This worked well for us. 这对我们很有用。 The rules are not particularly hard to write 这些规则并不是特别难写

One way to do it would be to modify the T4 templates in ASP.NET MVC that create forms, to have them insert this code automatically: 一种方法是修改ASP.NET MVC中创建表单的T4模板,让它们自动插入此代码:

<% using(Html.Form("UserProfile", "SubmitUpdate")) { %>
    <%= Html.AntiForgeryToken() %>
    <!-- rest of form goes here -->
<% } %>

And of course, you need the corresponding attribute on the controller method: 当然,您需要控制器方法上的相应属性:

[ValidateAntiForgeryToken]
public ViewResult SubmitUpdate()
{
    // ... etc
}

It's really not that difficult to retrofit an application in this manner, unless it's unusually large. 以这种方式改造应用程序并不困难,除非它非常大。 The last application I wrote in MVC would probably take me a couple of hours to retrofit. 我在MVC中写的最后一个应用程序可能需要几个小时才能进行改造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM