A security header is an HTTP response-header field that instructs clients or intermediaries to apply a security control. Configure these headers as part of preparing a web API for production. section 12.1.4
A production configuration can apply several controls through environment-aware middleware:
- Keep development-only Swagger and SwaggerUI middleware in the development branch. section 12.1.4
- In the non-development branch, enable HSTS and add response headers for framing, XSS protection, content-type sniffing, content security, and referrer policy. section 12.1.4
- Implement the headers with response middleware that adds fields to each response. section 12.1.4
Listing 12.1 Program.cs file: HTTP security headers
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
// HTTP Security Headers
app.UseHsts(); #1
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Frame-Options",
"sameorigin"); #2
context.Response.Headers.Add("X-XSS-Protection",
"1; mode=block"); #3
context.Response.Headers.Add("X-Content-Type-Options",
"nosniff"); #4
context.Response.Headers.Add("Content-Security-Policy",
"default-src ' self' ;"); #5
context.Response.Headers.Add("Referrer-Policy",
"strict-origin"); #6
await next();
});
}
Inspect the Program.cs listing to see the environment branch, HSTS call, and explicit response-header assignments. section 12.1.4
