设置ValidateAntiForgeryToken属性以在条件下工作

时间:2018-11-29 15:47:54

标签: c# asp.net-mvc csrf antiforgerytoken

我有一个带有POST动作的通用MVC控制器。该控制器用于多个应用程序使用的通用项目中。我们正在尝试在交错发布过程中添加CSRF保护,在此过程中,我们通过“防伪令牌”一次为每个应用程序添加CSRF保护。

如果将验证属性[ValidateAntiForgeryToken]添加到此控制器,但仅在其中1个应用程序的视图中包含“防伪令牌隐藏”表单元素,这将对其他应用程序造成破坏。如何根据条件应用此属性。这可能吗?是否需要像下面的代码一样手动完成?有更好的方法吗?

    [HttpPost]
    public ActionResult GenericSection(string nextController, string nextAction, FormCollection form)
    {
        // Validate anti-forgery token if applicable
        if (SessionHandler.CurrentSection.IncludeAntiForgeryToken)
        {
            try
            {
                AntiForgery.Validate();
            }
            catch (Exception ex)
            {
                // Log error and throw exception
            }
        }

        // If successful continue on and do logic
    }

1 个答案:

答案 0 :(得分:2)

如果使用ValidateAntiForgeryToken属性装饰控制器动作方法,则无法通过不在视图中放置隐藏字段来逃脱。

您需要找出一种方法,在其中具有ValidateAntiForgeryToken属性,在视图中具有令牌的隐藏字段,但仅在需要时验证令牌。

对于以下解决方案,我假设您正在谈论的多个应用程序都有web.config文件。

您需要做的是在appSettings中引入一个新配置,例如IsAntiForgeryTokenValidationEnabled或更短的名字。

如下创建一个新的属性类,并检查配置值。如果配置值为true,请继续验证令牌,否则只需跳过令牌即可。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CheckAntiForgeryTokenValidation : FilterAttribute, IAuthorizationFilter
{
    private readonly IIdentityConfigManager _configManager = CastleClassFactory.Instance.Resolve<IIdentityConfigManager>();
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var configValue = System.Configuration.ConfigurationManager.AppSettings["IsAntiForgeryTokenValidationEnabled"];
        //Do not validate the token if the config value is not provided or it's value is not "true".
        if(string.IsNullOrEmpty(configValue) || configValue != "true")
        {
            return;
        }
        // Validate the token if the configuration value is "true".
        else
        {
            new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
        }
    }
}
上面类的

OnAuthorization方法将在使用此属性的操作方法之前执行,并根据配置值验证或不验证令牌。

现在,您需要在控制器操作方法上使用此属性,如下例所示。

public class HomeController : Controller
{
     [HttpPost]
     [CheckAntiForgeryTokenValidation]
     public ActionResult Save()
     {
         // Code of saving.
     }
}

此后,所有要验证AntiForgeryToken的应用程序都需要在其配置文件中使用值为IsAntiForgeryTokenValidationEnabled的配置true。令牌验证默认情况下不可用,因此,如果现有应用程序没有配置,它们仍然可以正常工作。

我希望这可以帮助您解决问题。