Q:

AntiForgeryConfig.RequireSsl causes random errors when using without SSL

Our security team requires that all the cookies are set to Secure=true.
To set the secure property for MVC AntiForgery, we are using the following code:
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
    } 

But now we have a problem on our test server which is not using SSL. Sometimes we have spontaneous errors
The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.

When looking in the ASP.NET MVC code to pinpoint the location of the exception, we found the following
private void CheckSSLConfig(HttpContextBase httpContext)
{
    if (_config.RequireSSL && !httpContext.Request.IsSecureConnection)
    {
        throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL);
    }
}

It seems correct and it should work because the execution sequence is
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
    // ... something happens in between
        if (_config.RequireSSL && !httpContext.Request.IsSecureConnection)
        {
            throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL);
        }

But it seems that for some requests HttpContext.Current.Request.IsSecureConnection is returning true although we are not using SSL on our test server.
What's going on there? Why do we get this exception?

A:

I was searching for information about AntiForgeryConfig.RequireSsl and found your question.
In your following code:
protected void Application_BeginRequest(object sender, EventArgs e)
{
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
} 

You modify an application level value (AntiForgeryConfig.RequireSsl) with a local value (Request.IsSecureConnection).
If you have 2 requests with different Request.IsSecureConnection value, what do you think will happen ?
- first request set AntiForgeryConfig.RequireSsl to false
- second request set AntiForgeryConfig.RequireSsl to true
- first request is evaluated by CheckSSLConfig (true)
- second request is evaluated by CheckSSLConfig (true)
You must avoid modifying global application setting this way and write your own filter to handle that kind of behavior.

