I'm using the CSP module on my site and attempting to add a nonce to my GTM script.
I'm able to get a nonce value on the script element, e.g. <script nonce="zRaBCyoyymExSEt4jIfolw"> but that value never appears in my actual policy. I attempted to follow Altering a site's policy, but I'm confused on what I'm missing.
Here's my hook_page_attachments_alter().
function mytheme_page_attachments_alter(array &$attachments) {
$js = "nonce-aware GTM script";
$element = [
'#type' => 'html_tag',
'#tag' => 'script',
'#value' => Markup::create($js),
];
if (\Drupal::service('module_handler')->moduleExists('csp')) {
$placeholderKey = Drupal::service('csp.nonce_builder')->getPlaceholderKey();
// Add the nonce attribute to the element, with a placeholder value.
$element['#attributes']['nonce'] = $placeholderKey;
$element['#attached']['csp_nonce'] = [
// Nonces can only be applied to script or style elements, so a shorthand key is available.
// Values are an array of fallback sources.
'script' => [Csp::POLICY_UNSAFE_INLINE],
];
$element['#attached']['placeholders'][$placeholderKey] = [
'#lazy_builder' => ['csp.nonce_builder:renderNonce', []],
];
$attachments['#attached']['html_head']['custom_script'] = [
$element,
'custom_script',
'#weight' => '-1000'
];
}
}