Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CSP nonce without server side rendering (cookie)

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:

  • Server: Besides sending the nonce with the CSP header, also send it as a cookie (still changing for every request!) This also seems to be a common approach for CSRF
  • UI: instead of including the <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?

like image 773
True Random Avatar asked Jul 09 '26 07:07

True Random


1 Answers

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'
like image 112
ztom Avatar answered Jul 11 '26 20:07

ztom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!