Modifying security headers in Blazor
One of my recent “discoveries” is that I was not adding the correct headers to my applications. One of the client applications I've been building had a security review using this site: https://securityheaders.com/
As it turned out, I needed to make some tweaks, most of which you could do with the web.config files in previous versions of .NET. However, when you go to Blazor, the web.config is automatically generated. Instead of adding the header changes there, I had to add them to the Program.cs file. I placed them right at the end, just before the App.Run() line. These are the lines I added:
app.Use(async (context, next) =>
{
context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'; font-src *;img-src * data:; script-src *; style-src *;");
context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("Referrer-Policy", "strict-origin");
await next();
});
By adding these lines, I was able to get an A grade at SecurityHeaders.com. Make sure you're testing these settings before going live. I had another site where we were adding an iFrame from Authorize.net and adding the X-Frame-Options header caused this to break. However, leaving out the X-Frame-Options does not deduct from your score on this site.