- Issue created by @spfaffly
- πΊπΈUnited States spfaffly
I just noticed the hook_csp_policy_alter function. I was able to append using that hook by adding this function:
function hook_csp_policy_alter(Csp $policy, Response $response) { // Add nonce value to CSP. /** @var \Drupal\csp\PolicyHelper $policy_helper */ $policy_helper = \Drupal::service('csp.policy_helper'); $policy_helper->appendNonce($policy, 'script', ['unsafe-inline']); }
And then anywhere I needed to add the nonce value in my theme I used the Nonce service:
// Generate a nonce for CSP. /** @var \Drupal\csp\Nonce $nonce_service */ $nonce_service = \Drupal::service('csp.nonce'); $nonce_value = $nonce_service->getValue();
- π¨π¦Canada gapple
Your comment is correct.
Just make sure that your additional JS elements aren't being cached in the dynamic page cache if they're being added by something more granular thenhook_preprocess_page()
, so that they receive the new nonce value each time.2.1 should make this easier when it's released, by attaching information to the relevant render element and providing a placeholder for the nonce value β¨ Allow CSP to be added by render elements Needs review
- Status changed to Fixed
3 months ago 11:43pm 26 August 2024 - π¨π¦Canada gapple
Attaching policy to render elements is now available in a 2.1.0-beta1 release, and provides a mechanism to attach a nonce with a placeholder lazy builder so that the element can be cached and still receive a new nonce value on each request.
https://www.drupal.org/docs/extending-drupal/contributed-modules/contrib... β
Mhm, for some reason the hook isn't called in my module (but other hooks are):
function m_module_csp_policy_alter(\Drupal\csp\Csp $policy, \Symfony\Component\HttpFoundation\Response $response) { // Add nonce value to CSP. /** @var \Drupal\csp\PolicyHelper $policy_helper */ $policy_helper = \Drupal::service('csp.policy_helper'); $policy_helper->appendNonce($policy, 'style', ['unsafe-inline']); $policy_helper->appendNonce($policy, 'script', ['unsafe-inline']); }
Am I doing something wrong?
Ah, I see, it needs to be in a theme not in a module. Sadly the module contains nearly zero documentation :(
- π¨π¦Canada gapple
@defcon0 the theme hook is a relatively new addition specifically for themes, since they can't register a subscriber for the long-available Policy Alter event for modules.
I've done documentation updates alongside the 2.x releases to enumerate the options for dynamically altering the policy: https://www.drupal.org/docs/extending-drupal/contributed-modules/contrib... β
I personally learn best from functional examples, and the CSP module provides multiple examples by using the alter event itself. Automatically closed - issue fixed for 2 weeks with no activity.