azureasp.net-corehttpscontent-security-policystrict-transport-security

Strict-Transport-Security max-age not updating to 31536000 in ASP.NET Core application


I am trying to set the Strict-Transport-Security header in my ASP.NET Core application to enforce HTTPS with a max-age of 1 year (31536000 seconds), along with includeSubDomains and preload. However, when I check the headers in the browser, the max-age value is always set to 2592000 (30 days) instead of 31536000.

Here is the middleware code I am using:

app.Use(async (context, next) =>
{
    if (!env.IsDevelopment())
    {
        context.Response.Headers.Append("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
    }
    await next();
});

I have also verified that:

Why is the max-age value in the Strict-Transport-Security header not updating to 31536000? Is there any configuration in Azure or ASP.NET Core that might override this value?


Solution

  • To address your issue, it's important to configure HSTS (HTTP Strict Transport Security) properly in your ASP.NET Core application. Instead of manually appending headers, you should use the built-in HSTS middleware provided by ASP.NET Core. This ensures consistency and avoids potential conflicts with other configurations or hosting environments like Azure.

    Here’s how you can configure HSTS in the Program.cs file:

    builder.Services.AddHsts(options =>
    {
        options.Preload = true; // Enables the preload directive
        options.IncludeSubDomains = true; // Applies the policy to all subdomains
        options.MaxAge = TimeSpan.FromDays(365); // Sets max-age to 1 year (31536000 seconds)
        options.ExcludedHosts.Add("example.com"); // Example: Exclude certain hosts if needed
        options.ExcludedHosts.Add("www.example.com");
    });