### Basic Setup Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/configuration.md Registers the security headers middleware with default settings. ```csharp var builder = WebApplication.CreateBuilder(); var app = builder.Build(); app.UseSecurityHeaders(); app.Run(); ``` -------------------------------- ### Custom Header Examples Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/configuration.md Examples of adding and removing custom security headers. ```csharp // Add arbitrary headers policies.AddCustomHeader("X-Custom-Header", "value"); policies.AddCustomHeader("X-App-Version", "1.0.0"); // Remove headers added by other middleware policies.RemoveServerHeader(); policies.RemoveCustomHeaderExtensions("X-Powered-By"); // Per-request custom headers policies.AddCustomHeader("X-Correlation-Id", context => context.TraceIdentifier); ``` -------------------------------- ### Caching Static Policies Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/configuration.md Example of caching static policies at startup for performance. ```csharp // Create policies once at startup var apiPolicy = new HeaderPolicyCollection() .AddDefaultApiSecurityHeaders(); builder.Services.AddSecurityHeaderPolicies(policies => { policies.AddPolicy("Api", apiPolicy); // Reuse the same collection instance }); ``` -------------------------------- ### Program.cs Setup for Security Headers Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/tag-helpers.md Complete C# example for setting up Content-Security-Policy with various directives including nonce and hashed attributes in Program.cs. ```csharp var builder = WebApplication.CreateBuilder(); builder.Services.AddRazorPages(); builder.Services.AddSecurityHeaderPolicies(policies => { policies.SetDefaultPolicy(p => { p.AddContentSecurityPolicy(csp => { csp.AddUpgradeInsecureRequests(); csp.AddDefaultSrc().Self(); csp.AddScriptSrc() .Self() .WithNonce() .StrictDynamic(); csp.AddStyleSrc() .Self() .WithHashTagHelper(); csp.AddImgSrc().Self().Data(); }); }); }); var app = builder.Build(); app.UseSecurityHeaders(); app.MapRazorPages(); app.Run(); ``` -------------------------------- ### Cross-Origin-Resource-Policy Configuration Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/configuration.md Configures the Cross-Origin-Resource-Policy header. The example sets the policy to 'SameSite' to allow access from same-site origins. ```csharp policies.AddCrossOriginResourcePolicy(builder => { // Options: // - SameOrigin(): Only same-origin access // - SameSite(): Same-site access // - CrossOrigin(): Allow any cross-origin access builder.SameSite(); }); ``` -------------------------------- ### AddFullscreen() Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/permissions-policy-builder.md Example of allowing fullscreen for all. ```csharp builder.AddFullscreen().All(); ``` -------------------------------- ### Cross-Origin-Opener-Policy Configuration Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/configuration.md Configures the Cross-Origin-Opener-Policy header. The example sets the policy to 'SameOrigin' to isolate the document from cross-origin popups. ```csharp policies.AddCrossOriginOpenerPolicy(builder => { // Options: // - SameOrigin(): Isolate from cross-origin popups // - SameOriginAllowPopups(): Allow controlled popups // - UnsafeNone(): Allow any popups (not recommended) builder.SameOrigin(); }); ``` -------------------------------- ### Example Usage Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/middleware-extensions.md Example of configuring and using a named security policy. ```csharp // Configure the policy in Startup builder.Services.AddSecurityHeaderPolicies() .AddPolicy("DefaultPolicy", p => p.AddDefaultSecurityHeaders()); // Use it in the pipeline app.UseSecurityHeaders("DefaultPolicy"); ``` -------------------------------- ### Install the NuGet package Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/README.md Command to install the NetEscapades.AspNetCore.SecurityHeaders.TagHelpers NuGet package. ```bash dotnet package add Install-Package NetEscapades.AspNetCore.SecurityHeaders.TagHelpers ``` -------------------------------- ### Permissions-Policy Configuration Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/configuration.md Configures Permissions-Policy directives to control browser feature access. This example restricts camera, microphone, and geolocation, while allowing fullscreen and autoplay. ```csharp policies.AddPermissionsPolicy(builder => { builder.AddCamera().None(); builder.AddMicrophone().None(); builder.AddGeolocation().Self(); builder.AddFullscreen().All(); builder.AddAutoplay().Self(); }); ``` -------------------------------- ### Project file update Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/README.md Example of how the .csproj file is updated after installing the NuGet package. ```xml netcoreapp3.1 ``` -------------------------------- ### Middleware Position Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/middleware-extensions.md Example demonstrating the recommended placement of the security headers middleware early in the pipeline. ```csharp var app = builder.Build(); // Add security headers early! app.UseSecurityHeaders(); // Then add other middleware app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); ``` -------------------------------- ### Install using the .NET CLI Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/README.md Install the NetEscapades.AspNetCore.SecurityHeaders NuGet package using the dotnet CLI. ```bash dotnet add package NetEscapades.AspNetCore.SecurityHeaders --version 1.3.1 ``` -------------------------------- ### Header Composition Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/header-extensions.md Example demonstrating how to combine multiple security header policies. ```csharp var policies = new HeaderPolicyCollection() // Prevent clickjacking .AddFrameOptionsDeny() // Prevent MIME sniffing .AddContentTypeOptionsNoSniff() // Force HTTPS for 2 years including subdomains .AddStrictTransportSecurityMaxAgeIncludeSubDomains(63072000) // Control referrer leaks .AddReferrerPolicyStrictOriginWhenCrossOrigin() // Remove server information .RemoveServerHeader() // Add custom headers .AddCustomHeader("X-Custom-Header", "value") // CSP configuration .AddContentSecurityPolicy(builder => { builder.AddDefaultSrc().Self(); builder.AddScriptSrc().Self(); }); app.UseSecurityHeaders(policies); ``` -------------------------------- ### Complete CSP Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/csp-builder.md A comprehensive example demonstrating the configuration of various CSP directives. ```csharp app.UseSecurityHeaders(policies => { policies.AddContentSecurityPolicy(builder => { // Upgrade insecure requests and block mixed content builder.AddUpgradeInsecureRequests(); builder.AddBlockAllMixedContent(); // Default policy builder.AddDefaultSrc() .Self() .From("https://trusted-cdn.com"); // Scripts: self, nonce, and specific CDN builder.AddScriptSrc() .Self() .From("https://cdn.example.com") .WithNonce() .StrictDynamic(); // Styles: self, unsafe-inline, and Google Fonts builder.AddStyleSrc() .Self() .UnsafeInline() .From("https://fonts.googleapis.com") .WithHashTagHelper(); // Fonts builder.AddFontSrc() .Self() .From("https://fonts.gstatic.com"); // Restrict forms builder.AddFormAction().Self(); // Prevent framing builder.AddFrameAncestors().None(); // Disable plugins builder.AddObjectSrc().None(); // Base URI builder.AddBaseUri().Self(); // Reporting builder.AddReportUri() .To("https://report-uri.com/report/"); }); }); ``` -------------------------------- ### Complete Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/permissions-policy-builder.md This example demonstrates how to configure a Permissions-Policy, disabling most sensors and APIs while allowing fullscreen and picture-in-picture for the same origin, and specific domains for geolocation. ```csharp app.UseSecurityHeaders(policies => { policies.AddPermissionsPolicy(builder => { // Disable most sensors and APIs builder.AddAccelerometer().None(); builder.AddAmbientLightSensor().None(); builder.AddAutoplay().None(); builder.AddCamera().None(); builder.AddDisplayCapture().None(); builder.AddEncryptedMedia().None(); builder.AddGeolocation().None(); builder.AddGyroscope().None(); builder.AddMagnetometer().None(); builder.AddMicrophone().None(); builder.AddMidi().None(); builder.AddPayment().None(); builder.AddSpeaker().None(); builder.AddUsb().None(); builder.AddVR().None(); builder.AddXrSpatialTracking().None(); // Allow fullscreen builder.AddFullscreen().All(); // Allow picture-in-picture for same origin builder.AddPictureInPicture().Self(); // Allow geolocation for specific trusted domains builder.AddGeolocation() .Self() .For("https://maps.example.com"); }); }); ``` -------------------------------- ### GetNonce Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/tag-helpers.md C# example demonstrating how to retrieve a nonce and use it in manually-constructed HTML for script tags. ```csharp var nonce = HttpContext.GetNonce(); // Use in manually-constructed HTML var html = $""; ``` -------------------------------- ### AddCustomHeader() Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/header-extensions.md Example of adding custom headers like X-App-Version and X-Custom-Setting. ```csharp policies.AddCustomHeader("X-App-Version", "1.0.0"); policies.AddCustomHeader("X-Custom-Setting", "value"); ``` -------------------------------- ### Multi-Tenant Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/endpoint-extensions.md An example demonstrating how to apply different security header policies to different tenants by using a scoped service to determine the current tenant and select the appropriate policy. ```csharp builder.Services.AddScoped(); builder.Services.AddSecurityHeaderPolicies((policies, provider) => { policies.SetDefaultPolicy(p => p.AddDefaultSecurityHeaders()); policies.AddPolicy("TenantA", p => p .AddDefaultSecurityHeaders() .AddCustomHeader("X-Tenant", "A")); policies.AddPolicy("TenantB", p => p .AddDefaultSecurityHeaders() .AddCustomHeader("X-Tenant", "B")); policies.SetPolicySelector(context => { var tenantService = context.HttpContext.RequestServices .GetRequiredService(); var tenantId = tenantService.GetCurrentTenantId(context.HttpContext); var policyName = $"Tenant{tenantId}"; if (context.ConfiguredPolicies.TryGetValue(policyName, out var policy)) { return policy; } return context.DefaultPolicy; }); }); var app = builder.Build(); app.UseSecurityHeaders(); app.MapGet("/api/tenant-data", GetTenantData) .WithSecurityHeadersPolicy("TenantA"); app.Run(); ``` -------------------------------- ### Selective Feature Relaxation Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/permissions-policy-builder.md This example shows how to start with secure defaults and selectively enable features, such as camera, microphone, and fullscreen for specific origins. ```csharp policies.AddPermissionsPolicy(builder => { // Add all the default versions builder.AddDefaultSecureDirectives(); // Override a directive to allow a specific feature builder.AddCamera() .Self() .For("https://video-conference.example.com"); builder.AddMicrophone() .Self() .For("https://video-conference.example.com"); builder.AddFullscreen() .Self() .For("https://video.example.com"); }); ``` -------------------------------- ### Installation Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/README.md Install the NetEscapades.AspNetCore.SecurityHeaders NuGet package using the .NET CLI. ```bash dotnet add package NetEscapades.AspNetCore.SecurityHeaders ``` -------------------------------- ### Copy() Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/header-policy-collection.md Example of copying a default policy and adding a custom header. ```csharp var modifiedPolicy = defaultPolicy.Copy() .AddCustomHeader("X-Modified", "true"); ``` -------------------------------- ### AddAutoplay() Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/permissions-policy-builder.md Example of controlling autoplay. ```csharp builder.AddAutoplay().None(); ``` -------------------------------- ### SetScriptCSPHash Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/tag-helpers.md C# example demonstrating how to calculate and set a script CSP hash using HttpContext extensions. ```csharp var hash = CalculateSHA256("console.log('test')"); HttpContext.SetScriptCSPHash(CSPHashType.SHA256, hash); ``` -------------------------------- ### AddMediaSrc() Example Source: https://github.com/andrewlock/netescapades.aspnetcore.securityheaders/blob/main/_autodocs/api-reference/csp-builder.md Valid sources for