security-headers
Security headers configuration and best practices for ASP.NET Core Razor Pages applications. Covers CSP, HSTS, X-Frame-Options, and comprehensive security middleware setup. Use when configuring security headers in ASP.NET Core applications, implementing Content Security Policy (CSP), or setting up HSTS and other security-related HTTP headers.
What this skill does
You are a senior .NET security architect. When implementing security headers in Razor Pages applications, apply these patterns to protect against common web vulnerabilities like XSS, clickjacking, and man-in-the-middle attacks. Target .NET 8+ with nullable reference types enabled.
## Rationale
Security headers are a critical defense-in-depth mechanism that protect applications from various attacks without changing application code. Proper configuration can prevent XSS, clickjacking, MIME sniffing, and other common vulnerabilities. These headers are supported by all modern browsers.
## Security Headers Overview
| Header | Purpose | OWASP Category |
|--------|---------|----------------|
| **Content-Security-Policy** | Prevent XSS, data injection | A7 |
| **Strict-Transport-Security** | Force HTTPS connections | A2 |
| **X-Frame-Options** | Prevent clickjacking | A6 |
| **X-Content-Type-Options** | Prevent MIME sniffing | A6 |
| **Referrer-Policy** | Control referrer information | Privacy |
| **Permissions-Policy** | Restrict browser features | Privacy |
| **X-XSS-Protection** | Legacy XSS protection | A7 |
## Pattern 1: Built-in Security Headers Middleware
ASP.NET Core provides built-in middleware for common security headers.
```csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// HSTS (only in production)
if (!app.Environment.IsDevelopment())
{
app.UseHsts(); // Adds Strict-Transport-Security header
}
// HTTPS Redirection
app.UseHttpsRedirection();
// Security headers middleware (built-in .NET 8+)
// AddHeader can be used for custom headers
```
## Pattern 2: Custom Security Headers Middleware
For comprehensive control, create custom middleware.
```csharp
public class SecurityHeadersMiddleware(RequestDelegate next)
{
public async Task Invoke(HttpContext context)
{
// Prevent MIME sniffing
context.Response.Headers["X-Content-Type-Options"] = "nosniff";
// Prevent clickjacking
context.Response.Headers["X-Frame-Options"] = "DENY";
// Legacy XSS protection (redundant with CSP, but good for older browsers)
context.Response.Headers["X-XSS-Protection"] = "1; mode=block";
// Control referrer information
context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
// Permissions Policy (formerly Feature-Policy)
context.Response.Headers["Permissions-Policy"] =
"accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()";
await next(context);
}
}
// Extension method
public static class SecurityHeadersExtensions
{
public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app)
{
return app.UseMiddleware<SecurityHeadersMiddleware>();
}
}
```
### Registration
```csharp
// Program.cs
var app = builder.Build();
app.UseSecurityHeaders(); // Add early in pipeline
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
```
## Pattern 3: Content Security Policy (CSP)
CSP is the most powerful security header for preventing XSS and data injection attacks.
### Basic CSP Configuration
```csharp
public class CspMiddleware(RequestDelegate next, ILogger<CspMiddleware> logger)
{
private const string CspHeaderName = "Content-Security-Policy";
public async Task Invoke(HttpContext context)
{
var csp = new StringBuilder();
// Default fallback
csp.Append("default-src 'self'; ");
// Scripts: self + inline (nonce) + specific external sources
csp.Append("script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://js.stripe.com; ");
// Styles: self + inline + external CDNs
csp.Append("style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; ");
// Images: self + data URIs + external sources
csp.Append("img-src 'self' data: https: blob:; ");
// Fonts: self + Google Fonts
csp.Append("font-src 'self' https://fonts.gstatic.com; ");
// Connections (AJAX/WebSockets)
csp.Append("connect-src 'self' https://api.example.com wss://ws.example.com; ");
// Frames: only allow specific sources
csp.Append("frame-src 'self' https://js.stripe.com https://hooks.stripe.com; ");
// Form submissions
csp.Append("form-action 'self'; ");
// Base URI restrictions
csp.Append("base-uri 'self'; ");
// Prevent mixed content
csp.Append("upgrade-insecure-requests; ");
// Report violations (report-uri is deprecated, use report-to)
csp.Append("report-uri /api/csp-report; ");
context.Response.Headers[CspHeaderName] = csp.ToString();
await next(context);
}
}
```
### CSP with Nonce for Inline Scripts
```csharp
public class CspNonceMiddleware(RequestDelegate next)
{
public static readonly string NonceKey = "CSP-Nonce";
public async Task Invoke(HttpContext context)
{
// Generate cryptographically secure nonce
var nonce = GenerateNonce();
// Store in HttpContext for use in views
context.Items[NonceKey] = nonce;
// Add nonce to CSP header
var csp = $"script-src 'nonce-{nonce}' 'self'; " +
$"style-src 'nonce-{nonce}' 'self'; " +
"default-src 'self';";
context.Response.Headers["Content-Security-Policy"] = csp;
await next(context);
}
private static string GenerateNonce()
{
var bytes = new byte[16];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
return Convert.ToBase64String(bytes);
}
}
// Tag Helper for nonce
[HtmlTargetElement("script", Attributes = "asp-add-nonce")]
public class ScriptNonceTagHelper(IHttpContextAccessor httpContextAccessor) : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var nonce = httpContextAccessor.HttpContext?.Items[CspNonceMiddleware.NonceKey] as string;
if (!string.IsNullOrEmpty(nonce))
{
output.Attributes.SetAttribute("nonce", nonce);
}
}
}
// Usage in Razor view
<script asp-add-nonce>
console.log('This inline script is allowed because it has a nonce');
</script>
```
## Pattern 4: Configurable Security Headers
Allow different configurations per environment.
```csharp
public class SecurityHeadersOptions
{
public bool UseStrictCsp { get; set; } = true;
public List<string> AllowedScriptSources { get; set; } = new() { "'self'" };
public List<string> AllowedStyleSources { get; set; } = new() { "'self'" };
public List<string> AllowedImageSources { get; set; } = new() { "'self'", "data:", "https:" };
public bool UpgradeInsecureRequests { get; set; } = true;
public string? ReportUri { get; set; }
}
public class ConfigurableSecurityHeadersMiddleware(RequestDelegate next, IOptions<SecurityHeadersOptions> options, ILogger<ConfigurableSecurityHeadersMiddleware> logger)
{
private readonly SecurityHeadersOptions _options = options.Value;
public async Task Invoke(HttpContext context)
{
// Standard security headers
context.Response.Headers["X-Content-Type-Options"] = "nosniff";
context.Response.Headers["X-Frame-Options"] = "DENY";
context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
// Build CSP
var csp = new StringBuilder();
csp.Append($"default-src 'self'; ");
csp.Append($"script-src {string.Join(" ", _options.AllowedScriptSources)}; ");
csp.Append($"style-src {string.Join(" ", _options.AllowedStyleSources)}; ");
cspRelated in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.