A collection of middleware and methods for helping secure the headers for websites in .NET 6.
License
—
Deps
1
Install Size
—
Vulns
✓ 0
Published
Jan 31, 2024
$ dotnet add package IIR.SecurityHeaders.CoreThis plugin is for IIR .NET 6 and higher sites to add additional security to it.
You can easily add in the Program.cs file a few lines to quickly add additional security to your sites. (Upgraded projects might still have a Startup.cs)
We will want to try and make cookies as secure as possible with the following settings
// Sets the default cookie policy. You may need to apply additional policies for authentication.
builder.Services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Strict;
// Handling SameSite cookie according to https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1
options.HandleSameSiteCookieCompatibility(); // If you have a collision, use options.CustomHandleSameSiteCookieCompatibility();
options.HttpOnly = HttpOnlyPolicy.Always;
options.Secure = CookieSecurePolicy.Always;
});
// Configure HSTS to a year out and include pre-load and subdomains
builder.Services.AddHsts(o =>
{
o.Preload = true;
o.IncludeSubDomains = true;
o.MaxAge = TimeSpan.FromDays(365);
});
Add the following line to automatically add required security settings
app.UseIIRStandard();
app.UseCookiePolicy(); // This is to apply from the above section
Make sure that app.UseHsts(); is set in this method (usually is by default)
You will need to create a web.config file in the root of the website and add the following XML to it. This will help remove some of the header values we don't want to include
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By"/>
<remove name="Server" />
<remove name="X-AspNet-Version" />
<remove name="X-AspNetMvc-Version" />
</customHeaders>
</httpProtocol>
<security>
<requestFiltering removeServerHeader="true" />
</security>
</system.webServer>
</configuration>
In the _Viewimports.cshtml file you will want to add the following line to the file
@addTagHelper *, Joonasw.AspNetCore.SecurityHeaders
Most of this logic was taken from a library that has not been updated in a few years. We only inlcuded the tools that are still common for today. You can read more about the package at https://github.com/juunas11/aspnetcore-security-headers