Asp.net mvc AntiForgeryConfig.RequireSsl在不使用SSL的情况下使用时会导致随机错误

Asp.net mvc AntiForgeryConfig.RequireSsl在不使用SSL的情况下使用时会导致随机错误,asp.net-mvc,ssl,antiforgerytoken,Asp.net Mvc,Ssl,Antiforgerytoken,我们的安全团队要求将所有cookie设置为Secure=true 要设置MVC AntiForgery的安全属性,我们使用以下代码: protected void Application_BeginRequest(object sender, EventArgs e) { AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection; } protected

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

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

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
    } 
protected void Application_BeginRequest(object sender, EventArgs e)
{
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
} 
但是现在我们的测试服务器上出现了一个问题,它没有使用SSL。有时我们会有自发的错误

The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.
在ASP.NET MVC代码中查找异常的位置时,我们发现了以下内容

private void CheckSSLConfig(HttpContextBase httpContext)
{
    if (_config.RequireSSL && !httpContext.Request.IsSecureConnection)
    {
        throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL);
    }
}
它看起来是正确的,应该可以工作,因为执行顺序是正确的

    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
    // ... something happens in between
        if (_config.RequireSSL && !httpContext.Request.IsSecureConnection)
        {
            throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL);
        }
但对于某些请求,HttpContext.Current.Request.IsSecureConnection似乎返回true,尽管我们在测试服务器上没有使用SSL


那里发生了什么事?为什么会出现此异常?

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

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
    } 
protected void Application_BeginRequest(object sender, EventArgs e)
{
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
} 
您可以使用本地值(Request.IsSecureConnection)修改应用程序级值(AntiForgeryConfig.RequireSsl)

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


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

您最终找到了根本原因吗?我不确定-在我们将所有测试人员移至SSL后,错误似乎消失了。可能是因为有一段时间,我们的测试服务器上同时有http和https网站,浏览器中的反伪造cookie出错,将安全cookie发送到仅http的网站。无论如何,下一次使用https开发web应用程序时,我们必须记住这一点。我们也看到了一些类似的东西,但背景略有不同。我们在测试环境中安装了SSL,但没有将其用于探索性测试。如果我们删除证书,一切正常。如果我们配置SSL(但不使用https:URL),就会出现此错误。似乎仅限于1台机器,表明存在机器级配置\环境问题。