When building a web app with separated frontend and backend (no server side rendering) I still want to make use of CSP nonce. Usually the CSP header and the html should contain the same nonce, which is no problem with SSR but seems to be impossible without SSR.
Now I thought of a different way to make use of the nonce without SSR:
<script> which needs a nonce directly inside the html, rather load it dynamically from my own script: const script = document.createElement('script')
script.setAttribute('src', 'https://example.com')
script.setAttribute('data-csp-nonce', getCspNonceFromCookie())
document.head.appendChild(script);
Is this a valid approach for this problem? Are there security concerns?
Your solution works. One of my projects does it in a similar way. But you should set a nonce attribute instead of data-csp-nonce.
script.setAttribute('nonce', 'THE-GENERATED-NONCE')
So the script tag looks like:
<script nonce="jETnT70lr0T3Hw4b5WeCjuJ421a3kcBl">
// ...
</script>
This is only secure when the headers, send by the server, includes already content-security-policy which denies external scripts. E.g.:
content-security-policy: default-src 'self'; script-src 'self' 'nonce-jETnT70lr0T3Hw4b5WeCjuJ421a3kcBl'; img-src 'self' data:; object-src 'none'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With