HomeGuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityLog In

Content Security Policy

This topic 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, embeded JavaScripts are disabled when CSP is enabled. This means DXP and add-ons using our Client Resources functionality (for example) will fail to load. To enable these scripts, add a nonce to the script directive in the policy and also on the script element itself. 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 own nonce

Enable the CSP nonce by calling 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 how to configure and render the policy.

Use autogenerated nonce

By not specifying a function that returns a nonce, one will automatically be generated 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.


Did this page help you?