Home > Net >  How to Implement HSTS header in ASP.Net Core 6.0?
How to Implement HSTS header in ASP.Net Core 6.0?

Time:08-17

I need to implement the HSTS header security in the ASP.Net Core 6.0 WEB API application.

Below is my Program.cs

    var builder = WebApplication.CreateBuilder(args);
    ...
    // Https redirection
    builder.Services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
        options.HttpsPort = 7075;
    });
    
    // HSTS Security Headers 
    builder.Services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(365);
    });
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.UseCustomExceptionHandler();
    
    app.MapControllers();
    
    app.Run();

and below is the launchSettings.json

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:17240",
      "sslPort": 0
    }
  },
  "profiles": {
    "EFCoreRelationshipsTutorial": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5075;https://localhost:7075",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

The application launches on the URL - http://localhost:5075/swagger/index.html however, I was expecting it to be redirected to https://localhost:7075/swagger/index.html automatically.

Also, I was expecting the Strict Transport Security Header in the response like

enter image description here

however, it is not present in the response header.

enter image description here

What am I missing? How do I implement the HSTS in asp.net core 6.0?

CodePudding user response:

.AddHsts() excludes localhost which is why you're not seeing it working on your dev machine; and why it is only recommended to be used in production.

From the asp.net docs HTTP Strict Transport Security Protocol (HSTS):

UseHsts isn't recommended in development because the HSTS settings are highly cacheable by browsers. By default, UseHsts excludes the local loopback address.

For production environments that are implementing HTTPS for the first time, set the initial HstsOptions.MaxAge to a small value using one of the TimeSpan methods. Set the value from hours to no more than a single day in case you need to revert the HTTPS infrastructure to HTTP. After you're confident in the sustainability of the HTTPS configuration, increase the HSTS max-age value; a commonly used value is one year.

And then a snippet of code:

using System.Net;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

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");
});

builder.Services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
    options.HttpsPort = 5001;
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

The rest of the article explains the configuration options and behavior in more detail.

Edit: Testing UseHsts Locally

Just did a bit of experimenting and was able to get the Strict-Transport-Security header added to a Postman request by creating an entry in my Windows host file and updating my launchSettings.json.

Edit your hosts file; example on SuperUser.

File: C:\Windows\System32\drivers\etc\hosts

Add something along the lines of:

127.0.0.1 myweb.local

Save the file (you may need to open your editor in admin mode). And with the settings you posted, modify the host names from local host to the site name defined in the hosts file, i.e., myweb.local

"profiles": {
    "EFCoreRelationshipsTutorial": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://myweb.local:5075;https://myweb.local:7075",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
}

Granted, my environment only has https enabled, but the header was present after creating the entry in the hosts file and updating my launch settings to use the host name I mapped back to 127.0.0.1.

  • Related