liveBook · Manning

Security header

As explained in Building Web APIs with ASP.NET Core

An HTTP security header is an HTTP response-header field that instructs clients or intermediaries to apply a security control.

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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Shows environment-aware middleware and concrete header assignments, but does not explain each protection’s underlying attack mechanics.
Examples
Uses HSTS plus X-Frame-Options, X-XSS-Protection, X-Content-Type-Options, Content-Security-Policy, and Referrer-Policy assignments.
What it assumes
Assumes familiarity with Program.cs, runtime environments, and middleware configuration.
What you can do after
Operate/configure production response protections through environment-specific Program.cs middleware.
How it connects
Connects security headers with HTTP responses, middleware, HSTS, content security policy, and environment-specific configuration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.