When building or maintaining any website you should consider security hardening your HTTP security headers to prevent security vulnerabilities. Proper HTTP response headers can help prevent security vulnerabilities like Cross-Site Scripting, Clickjacking, Information disclosure and more. If you want read more details about each header a good reference is OWASP Secure Headers Project. Here I’ll demonstrate how this could be done in ASP.NET Core .NET 5.
First open your Startup.cs file in your application and go to the Configure method. Then implement the following code:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
// Security Headers
app.Use(async (context, next) =>
{
context.Response.Headers.Remove("Server");
context.Response.Headers.Remove("X-Powered-By");
context.Response.Headers.Add("X-Xss-Protection", "1; mode=block");
context.Response.Headers.Add("X-Frame-Options", "DENY");
context.Response.Headers.Add("Referrer-Policy", "no-referrer");
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("X-Permitted-Cross-Domain-Policies", "none");
context.Response.Headers.Add("Permissions-Policy", "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()");
context.Response.Headers.Add("Content-Security-Policy", "script-src 'self' safe-website.com;");
await next();
});
}
The important thing to point out above is the app.UseHsts(); this applies HTTP Strict Transport Security headers. The app.Use then removes the Server and X-Powered-By headers to prevent information disclosure about your server. The remaining headers are self explanatory, however please visit the OWASP Secure Headers Project for more details about each header and what values you should use for your specific requirements.
Once implemented, these values will be visible in your web page response headers through browser Developer Tools.