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

Set ValidateAntiForgeryToken Attribute to work on a condition

我有一个带有 POST 操作的通用 MVC 控制器。该控制器用于多个应用程序使用的公共项目。我们正在尝试在交错发布过程中添加 CSRF 保护,我们通过 Anti Forgery Token 一次为每个应用程序添加 CSRF 保护。

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

    [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
    }

如果你用ValidateAntiForgeryToken属性装饰控制器动作方法,你不能通过不把隐藏字段放在视图中来逃避。

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

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

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

如下创建新属性class并检查配置值。如果配置值为 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上面class的方法将在使用该属性的action方法之前执行,并根据配置值验证或不验证令牌。

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

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

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

希望这能帮助您解决问题。