Skip to content

Latest commit

ย 

History

History
314 lines (226 loc) ยท 10.7 KB

File metadata and controls

314 lines (226 loc) ยท 10.7 KB

๐Ÿ›ก๏ธ SafeWebCore

NuGet NuGet Downloads .NET 10 License: MIT securityheaders.com CSP Sponsor

SafeWebCore is a lightweight, high-performance .NET 10 middleware library that adds security headers to your ASP.NET Core applications. It targets an A+ rating on securityheaders.com out of the box โ€” zero configuration required.


โœจ Features

  • ๐Ÿ”’ A+ in one line โ€” AddNetSecureHeadersStrictAPlus() configures the strictest security headers instantly
  • ๐Ÿ› ๏ธ Fully custom โ€” AddNetSecureHeaders(opts => { ... }) gives you complete control over every header
  • ๐Ÿงฉ Nonce-based CSP โ€” per-request cryptographic nonces for script-src and style-src
  • ๐Ÿ“‹ Full CSP Level 3 (W3C Recommendation) โ€” all directives including worker-src, manifest-src, frame-src, script-src-elem/attr, style-src-elem/attr, report-to, nonce/hash support, strict-dynamic
  • ๐Ÿ”ฎ CSP Level 4 ready โ€” Trusted Types (require-trusted-types-for, trusted-types), fenced-frame-src (Privacy Sandbox)
  • ๐ŸŽฏ Fluent CSP Builder โ€” type-safe, chainable API with full XML documentation for every directive
  • โšก Zero-allocation nonce generation โ€” stackalloc + RandomNumberGenerator on the hot path, plus TryWriteNonce(Span<char>) for fully heap-free scenarios
  • ๐Ÿ” HttpContext.GetCspNonce() โ€” discoverable extension method to retrieve the per-request nonce
  • ๐Ÿ›‘ Server header removal โ€” hides server technology from attackers
  • ๐Ÿ”Œ Extensible โ€” add custom IHeaderPolicy implementations for any header
  • ๐Ÿ“Š CSP violation reporting โ€” built-in middleware for /csp-report endpoint using Reporting API v1

CSP Compliance

Standard Status Coverage
CSP Level 3 (W3C Recommendation) โœ… Full All 22 directives, nonce/hash, strict-dynamic, report-to
CSP Level 4 (Emerging) โœ… Ready Trusted Types, fenced-frame-src (Privacy Sandbox)

๐Ÿ†• What's New in v1.1.0

v1.1.0 is a performance and developer-experience release โ€” fully backwards compatible with v1.0.0.

Improvement Detail
Pre-built CSP template CSP header string is computed once at startup, not per-request
StringBuilder-based Build() Eliminates ~20 intermediate string allocations in CSP header generation
HttpContext.GetCspNonce() New extension method โ€” no more magic string lookups
NonceService.TryWriteNonce(Span<char>) Zero-allocation nonce generation for high-throughput paths
NonceService.NonceLength Public constant (44) for pre-allocating nonce buffers
CancellationToken in CSP reporting Report reads now respect client disconnects
Modern C# patterns Pattern matching, cleaner preset application, reduced boilerplate

See the full CHANGELOG for details.


๐Ÿš€ Quick Start

1. Install

dotnet add package SafeWebCore

2. One-line A+ setup (recommended)

using SafeWebCore.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Adds ALL security headers with the strictest A+ configuration
builder.Services.AddNetSecureHeadersStrictAPlus();

var app = builder.Build();

app.UseNetSecureHeaders();
app.MapGet("/", () => "Hello, secure world!");

app.Run();

That's it! Your application now returns these headers on every response:

Header Value
Strict-Transport-Security max-age=63072000; includeSubDomains; preload
X-Frame-Options DENY
X-Content-Type-Options nosniff
Referrer-Policy no-referrer
Permissions-Policy All features denied
Cross-Origin-Embedder-Policy require-corp
Cross-Origin-Opener-Policy same-origin
Cross-Origin-Resource-Policy same-origin
X-DNS-Prefetch-Control off
X-Permitted-Cross-Domain-Policies none
Content-Security-Policy Nonce-based, strict-dynamic, Trusted Types
Server (removed)

3. Strict A+ with customization

The preset is intentionally strict. Relax only what your app needs. CSP directives are space-separated โ€” add multiple origins in a single string:

builder.Services.AddNetSecureHeadersStrictAPlus(opts =>
{
    // Multiple CDNs โ€” just separate with spaces
    opts.Csp = opts.Csp with { ImgSrc = "'self' https://cdn1.example.com https://cdn2.example.com data:" };

    // Multiple directives at once using 'with { ... }'
    opts.Csp = opts.Csp with
    {
        ConnectSrc = "'self' https://api.example.com wss://ws.example.com",
        FontSrc = "'self' https://fonts.gstatic.com https://cdn.example.com"
    };

    // Non-CSP headers are simple string properties
    opts.ReferrerPolicyValue = "strict-origin-when-cross-origin";
});

๐Ÿ’ก Tip: Each CSP directive is one string with space-separated sources. Use a single with { ... } block to change multiple directives at once.

4. Full manual configuration

For complete control, use AddNetSecureHeaders with the fluent CSP builder:

using SafeWebCore.Builder;
using SafeWebCore.Extensions;

builder.Services.AddNetSecureHeaders(opts =>
{
    opts.EnableHsts = true;
    opts.HstsValue = "max-age=31536000; includeSubDomains";

    opts.EnableXFrameOptions = true;
    opts.XFrameOptionsValue = "SAMEORIGIN";

    opts.ReferrerPolicyValue = "strict-origin-when-cross-origin";

    // Use the fluent CSP builder
    opts.Csp = new CspBuilder()
        .DefaultSrc("'none'")
        .ScriptSrc("'nonce-{nonce}' 'strict-dynamic' https:")
        .StyleSrc("'nonce-{nonce}'")
        .ImgSrc("'self' https: data:")
        .FontSrc("'self' https://fonts.gstatic.com")
        .ConnectSrc("'self' wss://realtime.example.com")
        .FrameAncestors("'none'")
        .BaseUri("'none'")
        .FormAction("'self'")
        .UpgradeInsecureRequests()
        .Build();
});

๐Ÿ”‘ Using CSP Nonces in Razor Views

SafeWebCore generates a unique cryptographic nonce per request. Use it in your scripts and styles:

With the [CspNonce] attribute

using SafeWebCore.Attributes;

[CspNonce]
public class HomeController : Controller
{
    public IActionResult Index() => View();
}
<!-- In your Razor view -->
<script nonce="@ViewData["CspNonce"]">
    console.log("This script is allowed by CSP");
</script>

<style nonce="@ViewData["CspNonce"]">
    body { font-family: sans-serif; }
</style>

Direct access via GetCspNonce() extension (v1.1.0+)

using SafeWebCore.Extensions;

// In Minimal APIs, middleware, Razor Pages, etc.
var nonce = HttpContext.GetCspNonce();

Direct access via HttpContext.Items

var nonce = HttpContext.Items[NetSecureHeaders.CspNonceKey] as string;

๐Ÿ“Š CSP Violation Reporting

Enable the built-in CSP report endpoint to catch policy violations:

var app = builder.Build();

app.UseCspReport();           // Handles POST /csp-report
app.UseNetSecureHeaders();

app.Run();

Configure the CSP to send reports:

builder.Services.AddNetSecureHeadersStrictAPlus(opts =>
{
    opts.Csp = opts.Csp with { ReportTo = "default" };
});

Violations are logged at Warning level via ILogger.


๐Ÿ“ Project Structure

SafeWebCore/
โ”œโ”€โ”€ src/SafeWebCore/
โ”‚   โ”œโ”€โ”€ Abstractions/          # IHeaderPolicy interface
โ”‚   โ”œโ”€โ”€ Attributes/            # [CspNonce] action filter
โ”‚   โ”œโ”€โ”€ Builder/               # Fluent CspBuilder
โ”‚   โ”œโ”€โ”€ Constants/             # Header name constants
โ”‚   โ”œโ”€โ”€ Extensions/            # DI and middleware extensions
โ”‚   โ”œโ”€โ”€ Infrastructure/        # NonceService, CspReportMiddleware
โ”‚   โ”œโ”€โ”€ Middleware/             # NetSecureHeadersMiddleware
โ”‚   โ”œโ”€โ”€ Options/               # NetSecureHeadersOptions, CspOptions
โ”‚   โ””โ”€โ”€ Presets/               # SecurePresets (Strict A+)
โ”œโ”€โ”€ tests/SafeWebCore.Tests/   # xUnit v3 tests
โ”œโ”€โ”€ docs/                      # Documentation
โ””โ”€โ”€ .github/                   # CI, issue templates

๐Ÿ“š Documentation

Document Description
Getting Started Installation, first setup, verification
Security Headers Every header explained with rationale
CSP Configuration CSP builder, nonces, directives guide
Presets Strict A+ preset details and customization
Advanced Configuration Custom policies, reporting, per-route config

๐Ÿ—๏ธ Building & Testing

# Build
dotnet build

# Run tests
dotnet test

# Run tests with coverage
dotnet tool install -g dotnet-coverage
dotnet-coverage collect -f cobertura -o coverage.cobertura.xml dotnet test

โœ… Validate Your Security Headers

After deploying your application, verify your headers with these tools:

Scans all response headers and grades your site A+ through F. Validates HSTS, CSP, X-Frame-Options, Permissions-Policy, Referrer-Policy, and more.

With SafeWebCore's Strict A+ preset you should score A+ immediately.

Paste your Content-Security-Policy header value to check for common CSP misconfigurations:

  • โŒ Missing object-src 'none'
  • โŒ 'unsafe-inline' without a nonce or hash
  • โŒ Missing 'strict-dynamic' for trust propagation
  • โŒ Overly permissive wildcards (*, https:)
  • โœ… Nonce-based policy with 'strict-dynamic' (SafeWebCore default)

3. Browser DevTools

Open DevTools โ†’ Network tab โ†’ Response Headers to inspect headers on every request. Any CSP violations will also appear in the Console tab.


๐Ÿค Contributing

See CONTRIBUTING.md for guidelines.

๐Ÿ“„ License

This project is licensed under the MIT License. See LICENSE for details.

๐Ÿ“ Changelog

See CHANGELOG.md for release history.