The Problem with unsafe-inline
The unsafe-inline directive in CSP allows inline JavaScript and CSS to execute. While convenient, it significantly weakens your security because attackers can inject malicious inline scripts.
Why You Should Remove It
If your CSP includes unsafe-inline, an attacker who finds an XSS vulnerability can still execute arbitrary JavaScript. The whole point of CSP is defeated.
Solution 1: Use Nonces
A nonce is a random value generated for each request. Add it to your CSP and to each inline script:
CSP Header:
Content-Security-Policy: script-src 'nonce-abc123'
HTML:
<script nonce="abc123">
// Your inline code
</script>
The nonce must be unique per request and unpredictable.
Solution 2: Use Hashes
Calculate the SHA hash of your inline script and add it to CSP:
Content-Security-Policy: script-src 'sha256-base64hash...'
This works well for static inline scripts that do not change.
Solution 3: Move Inline Scripts to External Files
The cleanest solution is to move all JavaScript to external files:
<script src="/js/app.js"></script>
Handling Inline Event Handlers
Replace inline handlers like onclick="doSomething()" with addEventListener in your JavaScript files.
Test Your Changes
After making changes, scan your site with our CSP analyzer to verify unsafe-inline has been removed.