AntiForgeryConfig.RequireSsl 在没有 SSL 的情况下使用时会导致随机错误

Jus*_*tin 2 asp.net-mvc ssl antiforgerytoken

我们的安全团队要求将所有 cookie 设置为 Secure=true。

要为 MVC AntiForgery 设置安全属性,我们使用以下代码:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
    } 
Run Code Online (Sandbox Code Playgroud)

但是现在我们的测试服务器出现了一个问题,它没有使用 SSL。有时我们有自发的错误

The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.
Run Code Online (Sandbox Code Playgroud)

在查看 ASP.NET MVC 代码以查明异常的位置时,我们发现以下内容

private void CheckSSLConfig(HttpContextBase httpContext)
{
    if (_config.RequireSSL && !httpContext.Request.IsSecureConnection)
    {
        throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL);
    }
}
Run Code Online (Sandbox Code Playgroud)

这似乎是正确的,它应该可以工作,因为执行顺序是

    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
    // ... something happens in between
        if (_config.RequireSSL && !httpContext.Request.IsSecureConnection)
        {
            throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL);
        }
Run Code Online (Sandbox Code Playgroud)

但似乎对于某些请求 HttpContext.Current.Request.IsSecureConnection 返回 true 虽然我们没有在我们的测试服务器上使用 SSL。

那里发生什么事了?为什么我们会得到这个异常?

She*_*ron 6

我正在搜索有关 AntiForgeryConfig.RequireSsl 的信息并找到了您的问题。在您的以下代码中:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
} 
Run Code Online (Sandbox Code Playgroud)

您使用本地值 (Request.IsSecureConnection) 修改应用程序级别值 (AntiForgeryConfig.RequireSsl)。

如果您有 2 个具有不同 Request.IsSecureConnection 值的请求,您认为会发生什么?- 第一个请求将 AntiForgeryConfig.RequireSsl 设置为 false - 第二个请求将 AntiForgeryConfig.RequireSsl 设置为 true - 第一个请求由 CheckSSLConfig (true) 评估 - 第二个请求由 CheckSSLConfig (true) 评估

您必须避免以这种方式修改全局应用程序设置并编写自己的过滤器来处理这种行为。