To protect from XSS, configure CSP with nonce: (1) generate nonce each request ($nonce = base64_encode(random_bytes(16))); (2) add to header script-src 'nonce-{$nonce}'; (3) set nonce='{$nonce}' attribute on every inline <script>. No unsafe-inline.
Free online tool — CSP checker: instant results, no signup.
$nonce = base64_encode(random_bytes(16));. Must be a new nonce per request.header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{$nonce}'; style-src 'self' 'nonce-{$nonce}'; object-src 'none'; base-uri 'self'");<script nonce="<?= $nonce ?>">console.log('ok');</script>. Without nonce the script will be blocked.Content-Security-Policy-Report-Only: ...; report-uri /csp-report.php. Collect violations before enforcing.Content Security Policy (CSP) is a security feature that helps prevent Cross-Site Scripting (XSS) attacks by controlling which resources can be loaded on a webpage. One of the most effective ways to use CSP is through the nonce mechanism. A nonce (number used once) is a random value generated for each HTTP request that allows you to specify which scripts are safe to execute.
The nonce is included in your CSP header and must also be placed in the nonce attribute of each inline <script> tag. This creates a secure link between the CSP directive and the script, ensuring that only scripts with the correct nonce can be executed. If a script does not have the corresponding nonce, the browser will block it, thus enhancing your site's security.
To effectively implement the nonce mechanism, you must ensure that the nonce value is unique for each request. This uniqueness prevents attackers from reusing nonces to execute malicious scripts. Additionally, it is crucial to avoid using unsafe-inline in your CSP, as this would undermine the security intended by the nonce.
To configure CSP headers with nonce in a practical environment, follow these steps:
$nonce = base64_encode(random_bytes(16));header("Content-Security-Policy: script-src 'nonce-{$nonce}'");<script> tags. For example:<script nonce="{$nonce}">console.log('Hello, World!');</script>By following these steps, you can effectively implement a CSP with nonce, significantly enhancing your website's protection against XSS attacks.
Debugging issues related to CSP and nonce can be crucial for maintaining the security and functionality of your web application. Here are some common issues and how to troubleshoot them:
nonce attribute of your inline <script> tags. Mismatched values will lead to the browser blocking the script.By systematically addressing these issues, you can ensure that your CSP with nonce is functioning correctly, providing the intended protection against XSS attacks.
No for quick check. For continuous monitoring — free account.
Free plan — 10 monitors, checks every 5 min, no card required. Upgrade for 1-minute interval and multi-region monitoring.