This post gives you some code which will make your .NET 8 website more secure.
My friend Craig was asking for help with setting the security headers in his Umbraco 13 website. He isn't used to .NET 8 and had previously used the Startup.cs file to set the security headers in.
I quickly created a demo site, tested out this code and made sure it worked before sharing it with him.
First of all you need to create yourself a custom middleware class.
namespace MyProject.Middleware;
public sealed class SecurityHeadersMiddleware
{
private readonly RequestDelegate _next;
public SecurityHeadersMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
var headers = context.Response.Headers;
headers.Add("referrer-policy", "no-referrer");
headers.Add("x-content-type-options", "nosniff");
headers.Add("x-frame-options", "SAMEORIGIN");
headers.Add("x-permitted-cross-domain-policies", "none");
headers.Add("x-xss-protection", "1; mode=block");
headers.Add("permissions-policy", "accelerometer=(),autoplay=(),camera=(),display-capture=(),fullscreen=(),geolocation=(),gyroscope=(),magnetometer=(),microphone=(),midi=(),payment=()");
return _next(context);
}
}
Next you just need to update the Program.cs file to tell it to use that middleware.
In an Umbraco site you put it between the BootUmbracoAsync method and the UseUmbraco method like this:
await app.BootUmbracoAsync();
// add it in here
app.UseMiddleware<SecurityHeadersMiddleware>();
// add it in here
app.UseUmbraco()
Now when you run your site it will have these headers set in them and they will help your site be more secure. These are just some default settings, but you might want to change the settings or add some more headers such as a content security policy.
You can test your site's security headers find out more about them at SecurityHeaders.com