namespace DigitalData.Core.API
{
///
/// Middleware to add Content Security Policy (CSP) headers to the HTTP response.
///
public class CSPMiddleware
{
private readonly RequestDelegate _next;
private readonly string _policy;
///
/// Initializes a new instance of the class.
///
/// The next middleware in the request pipeline.
/// The CSP policy string with placeholders for nonces.
public CSPMiddleware(RequestDelegate next, string policy)
{
_next = next;
_policy = policy;
}
///
/// Invokes the middleware to add the CSP header to the response.
///
/// The HTTP context.
/// A task that represents the completion of request processing.
public async Task Invoke(HttpContext context)
{
// Generate a nonce (number used once) for inline scripts and styles
var nonce = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
// Store the nonce in the context items for later use
context.Items["csp-nonce"] = nonce;
// Add the CSP header to the response
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("Content-Security-Policy",
string.Format(_policy, nonce));
return Task.CompletedTask;
});
// Call the next middleware in the pipeline
await _next(context);
}
}
}