I'm using the mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim Linux docker image as a base for my .net core 3.1 web application running on a docker Linux container and I would like to add HSTS headers, but I've not been successful in doing that.

The first thing I tried was following the Microsoft documentation at https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-3.1&tabs=visual-studio for adding HSTS headers using the following code in the Startup.cs file as described by the documentation. I tried setting the HSTS values in the ConfigureServices(IServiceCollection services) method of Startup.cs by adding:

services.AddHsts(options => {
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(365); });

and then calling

app.UseHsts();
app.UseHttpsRedirection();

in the Configure(IApplicationBuilder app, IWebHostEnvironment env) method of Startup.cs, but they don't seem to work from there.

I thought that maybe the above method doesn't work when running in a Linux Docker container, so I tried looking for ways to set up the Strict-Transport-Security header in the Docker container, but I can't seem to figure out how to setup the correct values in the 3.1-buster-slim based container. The buster-slim container reports that it's using a version of nginx, but it seems to be a very slimmed down version and there isn't any documentation for the image that shows how to set HSTS headers. I've tried to use the HSTS documentation for nginx, but the buster-slim image doesn't seem to have the necessary software to configure HSTS this using that method.

Does anyone know of a way to set the HSTS headers from a Docker container based on the 3.1-buster-slim image or are there instructions that show how to add HSTS in the docker-compose file to set up HSTS for 3.1-buster-slim image based containers?

Thanks for any pointers toward a solution. Alan

I asked this question on the dotnet-docker github site, but was told to post this question on StackOverflow.

1

There are 1 best solutions below

0
On

My question was answered here: https://github.com/dotnet/dotnet-docker/issues/2268#issuecomment-714613811 by gsej on github. Here is the text and an image of the answer.

The issue here is that the middleware that adds the header (which you access with something like app.UseHsts()) will only add the header if the request is an https request. On the fact of it, this makes sense, but if you're running your dotnet core app in a docker container, then you might be terminating your SSL outside of the container (e.g. if you're hosting the container in an Azure AppService). The solution is to add your own tiny piece of middleware:

app.Use(async (context, next) => {
 context.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000");
 await next.Invoke();
});

GitHub screenshot of answer by gsej