skip to Main Content

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:

  • The application is running in the production environment (env.IsDevelopment() is false).
  • The browser cache has been cleared.
  • The application is deployed on Azure with HTTPS enabled.

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?

2

Answers


  1. Chosen as BEST ANSWER
    builder.Services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(60);
        options.ExcludedHosts.Add("example.com");
        options.ExcludedHosts.Add("www.example.com");
    });
    

  2. In addition to your Solution, check the below one

    Create a new Middleware Class file and add the below code.

    Thanks @meenakshiBalekar for the sample code.

    My Middleware.cs:

     public class Middleware
     {
         private readonly RequestDelegate _next;
    
         public Middleware(RequestDelegate next)
         {
             _next = next;
         }
    
         public async Task Invoke(HttpContext httpContext)
         {
             httpContext.Response.OnStarting(() =>
             {
                 httpContext.Response.Headers["strict-transport-security"] = "max-age=31536000; includeSubDomains; preload";
                 return Task.CompletedTask;
             });
             await _next(httpContext);
    
         }
     }
    
     public static class MiddlewareExtensions
     {
         public static IApplicationBuilder UseMiddleware(this IApplicationBuilder builder)
         {
             return builder.UseMiddleware<Middleware>();
         }
     }
    
    • Register this in Program.cs file:
    app.UseMiddleware<Middleware>();
    

    Output:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search