Content security policy
Describes how to prevent cross-site scripting attacks.
To prevent cross-site scripting (XSS) attacks, it is common to implement a Content Security Policy (CSP). By default, embedded JavaScripts are disabled when CSP is enabled. This means Optimizely Digital Experience Platform (DXP) and apps (add-ons) using Client Resources functionality (for example) will fail to load. Add a nonce to the policy's script directive and the script element itself to enable these scripts. See information about nonce.
ASP.NET does not have an API to add CSP, but third-party libraries can make this easy, and most of them already have an API for generating a nonce. However you construct and add the policy to the application, the Client Resource feature must know that a nonce should be added when rendering the script elements. You can do this in the following ways:
Bring your nonce
Enable the CSP nonce by calling the following in your startup and use the library's service to retrieve the nonce:
services.AddContentSecurityPolicyNonce(sp => sp.GetRequiredService<IThirPartyNonceProvider>().GetNonce());
Then, follow the library's recommendation on configuring and rendering the policy.
Use autogenerated nonce
Not specifying a function that returns a nonce will automatically generate one for each request.
services.AddContentSecurityPolicyNonce();
Then you can retrieve the generated nonce with ICspNonceService
so you can add the auto-generated nonce to the script directive in the policy also:
private readonly ICspNonceService _nonceService;
var policy = $"default 'self'; script-src 'nonce-{_nonceService.GetNonce()}' 'strict-dynamic'";
Note
In either case, you should add strict-dynamic to the script directive in your policy for best support.
Updated 6 months ago