Lesson 6 of 8
Content Security Policy & Security Headers
Security headers instruct browsers to enable built-in security mechanisms. CSP (Content Security Policy) is the most impactful - it whitelists sources of scripts, styles, and images, neutralizing most XSS attacks even if sanitization is bypassed.
Security Headers Middleware
// ━━ Security headers middleware - production configuration ━━
app.Use(async (context, next) =>
{
var headers = context.Response.Headers;
// Prevents MIME type sniffing (Chrome, Firefox)
headers["X-Content-Type-Options"] = "nosniff";
// Prevents clickjacking - no embedding in iframes
headers["X-Frame-Options"] = "DENY";
// Referrer information control
headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
// Disable browser features not needed by your app
headers["Permissions-Policy"] =
"camera=(), microphone=(), geolocation=(), payment=(), usb=()";
// HSTS - already added via app.UseHsts() but can be explicit:
if (!context.Request.IsHttps)
{
// handled by UseHttpsRedirection
}
// Content Security Policy - most important header
// For pure APIs (no browser rendering), use minimal CSP:
if (context.Request.Path.StartsWithSegments("/api"))
{
headers["Content-Security-Policy"] = "default-src 'none'"; // APIs don't render HTML
}
else
{
// Web pages:
headers["Content-Security-Policy"] =
"default-src 'self'; " +
"script-src 'self'; " + // JS from same origin only
"style-src 'self' 'unsafe-inline'; " + // CSS (unsafe-inline for dynamic styles)
"img-src 'self' data: https://cdn.myapp.com; " + // images from self + CDN
"font-src 'self' https://fonts.gstatic.com; " + // Google Fonts
"connect-src 'self' https://api.myapp.com; " + // XHR/fetch
"frame-ancestors 'none'; " + // equivalent to X-Frame-Options DENY
"upgrade-insecure-requests;"; // auto-upgrade HTTP to HTTPS
}
// Cross-Origin Resource Policy
headers["Cross-Origin-Resource-Policy"] = "same-origin";
headers["Cross-Origin-Opener-Policy"] = "same-origin";
await next();
});
// ━━ Helmet-like extension method ━━
public static class SecurityHeadersExtensions
{
public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app)
=> app.Use(async (ctx, next) =>
{
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
ctx.Response.Headers["X-Frame-Options"] = "DENY";
ctx.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
await next();
});
}
IApplicationBuilder app = null!;Tip
Tip
Practice Content Security Policy Security Headers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Content Security Policy Security Headers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Content Security Policy Security Headers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?