|
| 1 | +--- |
| 2 | +description: >- |
| 3 | + In this section, you will learn how to add a Content Security Policy (CSP) |
| 4 | + nonce to scripts & styles injected by Engage. |
| 5 | +--- |
| 6 | + |
| 7 | +# Content Security Policy nonce configuration |
| 8 | + |
| 9 | +Engage automatically injects different scripts and styles into the returned HTML when requesting content. It also adds the option to set a nonce for the duration of a request to be picked up and added to said scripts and styles. This can be used when a CSP requires a nonce for scripts.  |
| 10 | + |
| 11 | +{% hint style="info" %} |
| 12 | +This feature has been added in version 13.3.0+ of Engage. |
| 13 | +{% endhint %} |
| 14 | + |
| 15 | +## How to set a nonce |
| 16 | + |
| 17 | +Because a nonce should only be used once, it must be set in a location that gives control for individual requests. This could be in a Render Controller Action or a Service with lifetime Scoped or Transient. The following steps use a Render Controller to set a nonce. |
| 18 | + |
| 19 | +1. Get an instance of `IContentInjectionSecurityService` from the `Umbraco.Engage.Infrastructure.Common.Security` namespace into your controller using dependency injection.  |
| 20 | +2. Call the `.SetNonceForCurrentRequest("Your-Nonce-Here")` method before rendering content. |
| 21 | +3. Proceed as you to return content. |
| 22 | + |
| 23 | +```csharp |
| 24 | +public class HomeController : RenderController |
| 25 | +{ |
| 26 | + private readonly IContentInjectionSecurityService _contentInjectionSecurityService; |
| 27 | + |
| 28 | + public HomeController( |
| 29 | + ILogger<RenderController> logger, |
| 30 | + ICompositeViewEngine compositeViewEngine, |
| 31 | + IUmbracoContextAccessor umbracoContextAccessor, |
| 32 | + IContentInjectionSecurityService contentInjectionSecurityService) : base(logger, compositeViewEngine, umbracoContextAccessor) |
| 33 | + { |
| 34 | + _contentInjectionSecurityService = contentInjectionSecurityService; |
| 35 | + } |
| 36 | + |
| 37 | + public IActionResult Home() |
| 38 | + { |
| 39 | + _contentInjectionSecurityService.SetNonceForCurrentRequest("Your-Nonce-Here"); |
| 40 | + return base.Index(); |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +## Usage |
| 46 | + |
| 47 | +When a nonce is present for the current request, it will be added to the following locations: |
| 48 | + |
| 49 | +* The bot detection (ping) script within the Head tag. |
| 50 | +* The client-side analytics initializer script within the Body tag. |
| 51 | +* The cockpit scripts (only if the cockpit partial is added). |
| 52 | +* Any applied Personalization that makes use of CSS or Javascript. |
| 53 | + |
| 54 | +{% hint style="warning" %} |
| 55 | +Engage does not modify the existing CSP and doesn't set a nonce to scripts and styles added without Engage. |
| 56 | +{% endhint %} |
| 57 | + |
0 commit comments