Use app.UseCsp to define a Content Security Policy. The configuration allows you to define rules for various resource classes (Scripts, Styles, Images, etc.) and control where they can be loaded from using methods like .FromSelf(), .From(domain), or .FromNowhere() (to block entirely).
Key features include:
SetReportOnly(): Sends violation reports without blocking the resources.ReportViolationsTo(path): Specifies the endpoint for CSP violation reports.OnSendingHeader: A callback to conditionally skip sending the CSP header (e.g., for specific API routes).
// Content Security Policy
app.UseCsp(csp =>
{
// If nothing is mentioned for a resource class, allow from this domain
csp.ByDefaultAllow
.FromSelf();
// Allow JavaScript from:
csp.AllowScripts
.FromSelf() //This domain
.From("localhost:1591") //These two domains
.From("ajax.aspnetcdn.com");
// CSS allowed from:
csp.AllowStyles
.FromSelf()
.From("ajax.aspnetcdn.com");
// Allow Images from:
csp.AllowImages
.FromSelf();
// HTML5 audio and video elemented sources can be from:
csp.AllowAudioAndVideo
.FromNowhere();
// Contained iframes can be sourced from:
csp.AllowFrames
.FromNowhere(); //Nowhere, no iframes allowed
// Allow AJAX, WebSocket and EventSource connections to:
csp.AllowConnections
.To("ws://localhost:1591")
.To("http://localhost:1591")
.ToSelf();
// Allow fonts to be downloaded from:
csp.AllowFonts
.FromSelf()
.From("ajax.aspnetcdn.com");
// Allow object, embed, and applet sources from:
csp.AllowPlugins
.FromNowhere();
// Allow other sites to put this in an iframe?
csp.AllowFraming
.FromNowhere(); // Block framing on other sites, equivalent to X-Frame-Options: DENY
// Do not block violations, only report
csp.SetReportOnly();
// Where should the violation reports be sent to?
csp.ReportViolationsTo("/csp-report");
// Do not include the CSP header for requests to the /api endpoints
csp.OnSendingHeader = context =>
{
context.ShouldNotSend = context.HttpContext.Request.Path.StartsWithSegments("/api");
return Task.CompletedTask;
};
});