CSP basics
Learn to limit which sources can run scripts with Content Security Policy.
What is CSP?
Content Security Policy (CSP) is a security layer that tells the browser which sources may be loaded and run. It is set with an HTTP response header or a meta tag.
CSP greatly reduces the impact of XSS attacks. The default-src 'self' rule allows only same-origin sources; inline scripts and remote sources are blocked by default.
Selective permission with a nonce
A nonce is a random value that changes on each request and allows a single script tag. The CSP header uses script-src 'nonce-random'; the tag must carry the same value in its nonce attribute.
An attacker who injects a script cannot guess the right nonce, so it does not run. Nonces are the safe way to allow inline scripts selectively.
Exercise Add a nonce to a script
Write a function addNonce, parameters script and nonce. Assign the nonce value with script.nonce = nonce. Then add it to the head with document.head.appendChild(script).
Show example solution
First define the function, then assign the value to script.nonce, finally append to the head.
Example solution:
function addNonce(script, nonce) {
script.nonce = nonce;
document.head.appendChild(script);
}
Test yourself
-
Which CSP directive allows scripts only from the same origin?
- script-src 'unsafe-inline'
- script-src 'self'
- script-src '*'
- default-src 'unsafe-eval'
Show answer
script-src 'self' — Correct! script-src 'self' allows scripts only from the same origin.
-
Complete the CSP rule
const policy = "default-src ____";Show answer
const policy = "default-src 'self'"; -
Match the CSP directives
- default-src
- general default
- script-src
- script sources
- style-src
- style sources
- img-src
- image sources