FoxLearn.AspNetCore.SecurityHeaders
2.0.1
dotnet add package FoxLearn.AspNetCore.SecurityHeaders --version 2.0.1
NuGet\Install-Package FoxLearn.AspNetCore.SecurityHeaders -Version 2.0.1
<PackageReference Include="FoxLearn.AspNetCore.SecurityHeaders" Version="2.0.1" />
<PackageVersion Include="FoxLearn.AspNetCore.SecurityHeaders" Version="2.0.1" />
<PackageReference Include="FoxLearn.AspNetCore.SecurityHeaders" />
paket add FoxLearn.AspNetCore.SecurityHeaders --version 2.0.1
#r "nuget: FoxLearn.AspNetCore.SecurityHeaders, 2.0.1"
#:package FoxLearn.AspNetCore.SecurityHeaders@2.0.1
#addin nuget:?package=FoxLearn.AspNetCore.SecurityHeaders&version=2.0.1
#tool nuget:?package=FoxLearn.AspNetCore.SecurityHeaders&version=2.0.1
🔷 FoxLearn.AspNetCore.SecurityHeaders
FoxLearn.AspNetCore.SecurityHeaders is a lightweight library for adding common security headers to ASP.NET Core applications.
This package simplifies the process of applying essential HTTP security headers—such as Content-Security-Policy
, Strict-Transport-Security
, X-Content-Type-Options
, and more—to your ASP.NET Core middleware pipeline, helping protect your web applications from common vulnerabilities.
✅ Features
🔒 Easy integration with ASP.NET Core middleware
⚙️ Predefined defaults for recommended security headers
🛠️ Fully customizable header values
💡 Supports .NET 3.1 and later
📥 Installation
Install via the .NET CLI:
dotnet add package FoxLearn.SecurityHeaders.AspNetCore
Or via the NuGet UI in Visual Studio by searching for FoxLearn.AspNetCore.SecurityHeaders
🧪 Usage
To enable and customize security headers in your ASP.NET Core application, configure the services and middleware using the provided extension methods. Add the service registration in your Startup.cs
or Program.cs
file:
builder.Services.AddSecurityHeaderPolicies(options =>
{
options.AddCrossOriginResourcePolicy(x => x.SameOrigin())
.AddFrameOptionsDeny()
.AddContentTypeOptionsNoSniff()
.AddReferrerPolicy(ReferrerPolicy.StrictOrigin)
.AddStrictTransportSecurity()
.AddPermissionsPolicy(policy =>
{
policy.AddAccelerometer().Self().For("https://foxlearn.com");
policy.AddMicrophone();
});
});
var app = builder.Build();
...
app.UseSecurityHeaders(); // Required
Alternatively, to apply the default security headers, simply use: DefaultSecurityHeaders
builder.Services.AddSecurityHeaderPolicies(options =>
{
options.AddDefaultSecurityHeaders();
});
To fully control the headers returned, create a HeaderPolicyCollection
and define your own set of headers including any custom headers you may need:
// Define a custom header policy
var policy = new HeaderPolicyCollection()
.AddFrameOptionsDeny()
.AddReferrerPolicyStrictOriginWhenCrossOrigin();
builder.Services.AddSecurityHeaderPolicies(options =>
{
options.AddPolicy("CustomPolicy", policy => policy.AddCustomHeader("X-Custom", "SomeValue"));
});
// Apply your custom policy globally or on a per-endpoint basis:
app.UseSecurityHeaders(policy); // Apply custom global policy
app.UseEndpointSecurityHeaders(); // Enable attribute-based usage
📘 Apply a Policy to a Controller Action
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[SecurityHeadersPolicy("CustomPolicy")]
public IActionResult Index()
{
return View();
}
}
📘 Apply custom policies to endpoints
If you need to apply a custom (non-default) security header policy to a specific endpoint, use the .WithSecurityHeadersPolicy("PolicyName")
extension method during endpoint mapping:
app.MapGet("/", () => "Hello world")
.WithSecurityHeadersPolicy("CustomPolicy"); // Apply a named policy to this endpoint
📘 RemoveServerHeader
The RemoveServerHeader method is usually not enough to fully eliminate the Server header from HTTP responses. This is because middleware earlier in the pipeline can remove it, but Kestrel typically appends the Server header after middleware runs making it difficult to override at that stage.
To properly prevent the Server header from being added, you should configure Kestrel directly:
var host = new WebHostBuilder()
.UseKestrel(options => options.AddServerHeader = false)
Make sure this is set in Program.cs
when building your app’s WebHostBuilder
. This disables the automatic inclusion of the Server header at the source the Kestrel web server itself.
📘 Using Nonces and generated-hashes with Content-Security-Policy
Using a secure Content-Security-Policy (CSP) can be challenging when your application includes inline scripts, styles, or other resources that aren't explicitly allow-listed. There are two recommended approaches to safely include such content:
Nonces: A unique value (nonce) is generated per request, added to the CSP header, and applied to individual
<script>
or<style>
tags.Hashes: The SHA-256 hash of the inline content is calculated and included in the CSP header to allow that specific content.
To use nonces or hashes in ASP.NET Core, follow these steps:
Open _ViewImports.cshtml
, then import
@addTagHelper *, FoxLearn.AspNetCore.SecurityHeaders
This makes the tag-helper available in your Razor views.
Configure CSP to Use Nonces and Hashes
When setting up your Content Security Policy (CSP), you can enhance flexibility and maintain strong security by using nonces and hashes:
builder.Services.AddSecurityHeaderPolicies(options =>
{
options.AddContentSecurityPolicy(policy =>
{
policy.AddUpgradeInsecureRequests();
policy.AddScriptSrc().Self().UnsafeHashes().Nonce();
policy.AddStyleSrc().Self().UnsafeHashes();
});
});
To securely allow inline scripts or styles under a strict Content Security Policy (CSP), you can add the csp-nonce attribute to HTML elements. This activates the NonceTagHelper, which automatically injects a unique nonce into the element and the CSP header, enabling it to be safely executed without relaxing security via 'unsafe-inline'.
<script csp-nonce>
document.addEventListener('DOMContentLoaded', function () {
const logDiv = document.createElement('div');
logDiv.style.padding = '10px';
logDiv.style.backgroundColor = '#eef';
logDiv.style.border = '1px solid #ccd';
logDiv.innerText = "Current time: " + new Date().toLocaleTimeString();
document.body.appendChild(logDiv);
});
</script>
A unique nonce is generated for each request and automatically attached to elements at runtime. This results in markup like:
<script nonce="kjJXffTiKZ+i8luIwbAA6sEg5owOf3wVKdvIQjm955U=">
document.addEventListener('DOMContentLoaded', function () {
const logDiv = document.createElement('div');
logDiv.style.padding = '10px';
logDiv.style.backgroundColor = '#eef';
logDiv.style.border = '1px solid #ccd';
logDiv.innerText = "Current time: " + new Date().toLocaleTimeString();
document.body.appendChild(logDiv);
});
</script>
Your ouput header should like:
content-security-policy: upgrade-insecure-requests ; script-src 'self' 'unsafe-inline' 'nonce-kjJXffTiKZ+i8luIwbAA6sEg5owOf3wVKdvIQjm955U='; style-src 'self' 'unsafe-hashes' 'nonce-kjJXffTiKZ+i8luIwbAA6sEg5owOf3wVKdvIQjm955U=';
To allow specific inline <script>
or <style>
blocks under CSP using hashes, apply the asp-add-content-to-csp attribute. This activates the HashTagHelper, which automatically computes the content hash and includes it in the CSP header.
You can optionally specify the hash algorithm using the csp-hash-type attribute (e.g., SHA256, SHA384, or SHA512).
<script csp>
const notice = document.getElementById('notice');
if(notice != null){
notice.textContent = "This script is securely allow-listed via CSP hash.";
}
</script>
<style csp csp-hash-type="SHA512">
#notice {
font-weight: bold;
color: green;
margin-top: 20px;
}
</style>
At runtime, the csp attribute is automatically removed from the HTML output. Meanwhile, the hash of the element's content is calculated and added to the Content-Security-Policy header, allowing the inline script or style to execute securely.
Inline styles and event handlers do not support nonces in Content Security Policy (CSP). Instead, you can use the AttributeHashTagHelper, which hashes specific attributes using a special csp-for-* attribute (where * is the attribute name, like style or onclick). This helper removes these attributes at runtime and adds the corresponding hash values to the CSP header, ensuring security.
<h2 csp-for-style style="color: blue">I will be styled blue</h2>
You can also specify the hash algorithm (SHA256, SHA384, or SHA512) by setting it on the csp-for-* attribute.
<button csp-for-style style="color: blue" csp-for-onclick="SHA384" onclick="alert('Hello!')">Click me!</button>
🔒 License
This project is licensed under the MIT License. Free for personal and commercial use.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 is compatible. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
.NET Core | netcoreapp3.1 is compatible. |
-
.NETCoreApp 3.1
- No dependencies.
-
net5.0
- No dependencies.
-
net6.0
- No dependencies.
-
net7.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.