Internet Frontend 06 ๐ Content Security Policy and Security Headers
Security headers are HTTP response headers that instruct the browser to enforce a security policy on the page. They are declarative: the server declares what is allowed, and the browser blocks everything else. The Content Security Policy is the most powerful of these headers, because it controls which resources the page can load and which scripts it can execute. The other headersโStrict-Transport-Security, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policyโeach address a specific class of attack, and the combination is the defense-in-depth layer that sits between the application and the attacker.
The CSP is not a single header value. It is a policy with multiple directives, each controlling a different resource type. The script-src directive controls the scripts, the style-src controls the styles, the img-src controls the images, and the default-src is the fallback for the directives that are not explicitly set . The policy is enforced by the browser, and a violation is reported in the console. The reporting can also be configured with the report-uri directive, which sends the violation details to a server endpoint .
Key point: A strict CSP uses nonces or hashes instead of allow-lists, and the strict-dynamic directive extends the trust to the scripts that the trusted scripts create . The X-Frame-Options and the CSP frame-ancestors directive both mitigate clickjacking, but frame-ancestors is the more flexible and the preferred mechanism . The X-Content-Type-Options: nosniff header prevents the browser from MIME-sniffing a response away from the declared content type .
Why the security headers are a layered defense
The CSP problem. The CSP is the primary defense against cross-site scripting (XSS) and content injection. The older allow-list approachโlisting the trusted domains in the script-src directiveโis easy to bypass, because an attacker who can upload a script to a trusted domain can execute it. The current leading practice is the strict CSP, which uses a per-response nonce or a script hash instead of a domain allow-list . The nonce is a random value that the server generates for each response and adds to the script-src directive. The inline script must carry the matching nonce attribute, and the browser executes only the scripts that have the correct nonce .
The clickjacking problem. Clickjacking is the attack where the malicious site embeds the trusted site in an <iframe> and overlays the UI elements to trick the user into clicking the wrong thing. The X-Frame-Options header with the DENY or SAMEORIGIN value blocks the embedding, and the CSP frame-ancestors directive is the more granular replacement . The frame-ancestors 'none' is the equivalent of DENY, and the frame-ancestors 'self' is the equivalent of SAMEORIGIN. The frame-ancestors directive can also specify the allowed parent origins, which is the capability that X-Frame-Options does not have .
The MIME-sniffing problem. The browser can sniff the content of a response and decide to treat it as a different type than the server declared. A response that the server declares as text/plain can be sniffed as text/html and executed as a script, which is the classic XSS vector. The X-Content-Type-Options: nosniff header tells the browser to trust the declared content type and refuse to execute the response if it does not match . The header is a strict contract: the server that sends it must supply the correct Content-Type for every resource.
The transport problem. The Strict-Transport-Security (HSTS) header tells the browser to always use HTTPS for the domain, even if the user types http://. The max-age directive is the time-to-live for the policy, and the includeSubDomains directive extends the policy to the subdomains . The HSTS is the mechanism that prevents the SSL-stripping attack, where the attacker intercepts the initial HTTP request and redirects the user to the malicious site.
a. The Content Security Policy directives
The CSP is a semicolon-separated list of directives. The default-src is the fallback, and the specific directives override it for the resource type they control. The script-src is the most important directive, because the script execution is the XSS vector.
Content-Security-Policy: default-src 'self'; script-src 'nonce-abc123' 'strict-dynamic'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
The default-src 'self' allows the resources from the same origin. The script-src 'nonce-abc123' 'strict-dynamic' allows the scripts that carry the nonce and the scripts that those scripts create. The object-src 'none' blocks the plugins. The base-uri 'self' restricts the <base> element, which is the vector for the base-tag injection attack. The frame-ancestors 'none' blocks the embedding .
The nonce is the per-response random value. The server generates it for each request and injects it into the CSP header and the script tags.
<script nonce="abc123">
// The inline script is allowed because it has the nonce.
</script>
The hash is the alternative to the nonce. The script-src 'sha256-...' allows the specific inline script whose content matches the hash. The hash is calculated from the exact script content, including the whitespace, so a formatting change invalidates the hash . The hash is the right choice for a static inline script that does not change, and the nonce is the right choice for the dynamic scripts.
b. The other security headers
The Strict-Transport-Security header is the HSTS mechanism. The max-age is the duration in seconds, and the includeSubDomains extends the policy.
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
The max-age=31536000 is one year. The preload directive is the request to include the domain in the browser’s preloaded HSTS list, which is the mechanism that protects the first visit, before the header has been received .
The X-Frame-Options header is the clickjacking defense. The DENY blocks all embedding, and the SAMEORIGIN allows the same-origin embedding.
X-Frame-Options: DENY
The X-Content-Type-Options: nosniff header is the MIME-sniffing defense.
X-Content-Type-Options: nosniff
The Referrer-Policy header controls the amount of the referrer information that is sent with the requests. The strict-origin-when-cross-origin is the modern default: it sends the full URL for the same-origin requests, the origin only for the cross-origin requests, and no referrer for the downgrade (HTTPS to HTTP) .
Referrer-Policy: strict-origin-when-cross-origin
The Permissions-Policy header controls the browser features that the page and its iframes can use. The camera=() blocks the camera, and the geolocation=() blocks the geolocation .
Permissions-Policy: camera=(), microphone=(), geolocation=()
Complete Example Session
// ============================================
// PART 1: THE CSP HEADER
// ============================================
// The nonce-based strict CSP.
const nonce = crypto.randomUUID();
res.setHeader(
'Content-Security-Policy',
`default-src 'self'; script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'`
);
// The nonce is injected into the script tags.
// <script nonce="${nonce}">...</script>
// ============================================
// PART 2: THE HSTS HEADER
// ============================================
res.setHeader(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload'
);
// The browser uses HTTPS for the domain for one year.
// The preload directive requests the inclusion in the browser's preload list.
// ============================================
// PART 3: THE CLICKJACKING HEADERS
// ============================================
res.setHeader('X-Frame-Options', 'DENY');
// The CSP frame-ancestors is the modern replacement.
// Both are set for the older browser support.
// ============================================
// PART 4: THE MIME-SNIFFING HEADER
// ============================================
res.setHeader('X-Content-Type-Options', 'nosniff');
// The browser trusts the Content-Type header.
// The server must supply the correct Content-Type.
// ============================================
// PART 5: THE REFERRER POLICY
// ============================================
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// The full URL for same-origin, the origin for cross-origin.
// No referrer for the downgrade.
// ============================================
// PART 6: THE PERMISSIONS POLICY
// ============================================
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
// The camera, microphone, and geolocation are blocked.
// ============================================
// PART 7: THE CSP REPORTING
// ============================================
// The report-uri directive sends the violations.
res.setHeader(
'Content-Security-Policy',
`...; report-uri /csp-report`
);
// The server receives the JSON report.
// { "csp-report": { "document-uri": "...", "blocked-uri": "...", ... } }
// ============================================
// PART 8: THE HELMET MIDDLEWARE
// ============================================
// The Express middleware that sets the headers.
import helmet from 'helmet';
app.use(helmet());
// The helmet sets the CSP, HSTS, X-Frame-Options, X-Content-Type-Options,
// Referrer-Policy, and Permissions-Policy by default.
// ============================================
// PART 9: THE VERIFICATION
// ============================================
// The browser's network tab shows the response headers.
// The console shows the CSP violations.
// The securityheaders.com scanner shows the header grade.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The CSP uses a nonce or hash, not an allow-list.
// [ ] The strict-dynamic directive is set if the trusted scripts create scripts.
// [ ] The frame-ancestors directive is set.
// [ ] The X-Frame-Options is set for the older browsers.
// [ ] The HSTS max-age is at least one year.
// [ ] The X-Content-Type-Options is nosniff.
// [ ] The Referrer-Policy is strict-origin-when-cross-origin.
// [ ] The Permissions-Policy blocks the unused features.
The ten parts covered the CSP header, the HSTS header, the clickjacking headers, the MIME-sniffing header, the Referrer-Policy, the Permissions-Policy, the CSP reporting, the Helmet middleware, the verification, and the checklist. The through-line is that the headers are a layered defense, and the CSP is the most powerful layer.
Quick Reference
The security headers
| Header | Purpose | Recommended value |
|---|---|---|
Content-Security-Policy | Controls the resource loading | Nonce-based strict policy |
Strict-Transport-Security | Forces HTTPS | max-age=31536000; includeSubDomains |
X-Frame-Options | Blocks clickjacking | DENY or SAMEORIGIN |
X-Content-Type-Options | Blocks MIME-sniffing | nosniff |
Referrer-Policy | Controls the referrer | strict-origin-when-cross-origin |
Permissions-Policy | Controls the browser features | camera=(), microphone=() |
The CSP directives
| Directive | Controls |
|---|---|
default-src | The fallback for the other directives |
script-src | The script execution |
style-src | The stylesheets |
img-src | The images |
object-src | The plugins |
frame-ancestors | The embedding parents |
base-uri | The <base> element |
The clickjacking equivalents
| CSP | X-Frame-Options | Effect |
|---|---|---|
frame-ancestors 'none' | DENY | No embedding |
frame-ancestors 'self' | SAMEORIGIN | Same-origin embedding only |
frame-ancestors https://example.com | (not supported) | Specific origin |
Best Practices
โ Do This:
Content-Security-Policy: default-src 'self'; script-src 'nonce-abc123' 'strict-dynamic'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options: nosniff
โ Don’t Do This:
Content-Security-Policy: script-src 'unsafe-inline' 'unsafe-eval'
X-Frame-Options: ALLOW-FROM https://example.com
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The CSP is bypassed | The allow-list includes a domain that hosts user content | Use a nonce or hash |
| The inline script is blocked | The nonce is missing on the script tag | Add the nonce attribute |
| The clickjacking defense is missing | The X-Frame-Options is not set | Set DENY or SAMEORIGIN |
| The HSTS is not applied | The header is sent over HTTP | The HSTS is ignored over HTTP |
| The MIME-sniffing is not blocked | The nosniff header is missing | Set X-Content-Type-Options: nosniff |
Summary
| Item | Value |
|---|---|
| CSP | The resource loading policy; nonce or hash for the strict mode |
| HSTS | The HTTPS enforcement with max-age |
| X-Frame-Options | The clickjacking defense; DENY or SAMEORIGIN |
| X-Content-Type-Options | The MIME-sniffing defense; nosniff |
| Referrer-Policy | The referrer control; strict-origin-when-cross-origin |
| Permissions-Policy | The browser feature control |
Key takeaways:
- The strict CSP uses a nonce or a hash, not an allow-list. The allow-list is bypassable if the trusted domain hosts the user content. The nonce is the per-response random value, and the hash is the exact script content . The
strict-dynamicdirective extends the trust to the scripts that the trusted scripts create. - The clickjacking defense is the
X-Frame-Optionsor the CSPframe-ancestors. Theframe-ancestorsis the more flexible and the preferred mechanism, because it can specify the allowed parent origins. TheX-Frame-Optionsis the older header, and it is set for the legacy browser support . - The
X-Content-Type-Options: nosniffis the MIME-sniffing defense. The browser trusts the declaredContent-Typeand refuses to execute the response if it does not match. The server must supply the correct content type for every resource . - The HSTS forces the HTTPS. The
max-ageis the time-to-live for the policy, and theincludeSubDomainsextends the policy to the subdomains. Thepreloaddirective requests the inclusion in the browser’s preload list . - The headers are a layered defense. The CSP is the primary defense against XSS, the HSTS is the transport defense, the X-Frame-Options is the clickjacking defense, and the X-Content-Type-Options is the MIME-sniffing defense. The combination is the defense-in-depth layer.
Remember: The security headers are declarative policies that the browser enforces. The CSP is the most powerful, because it controls the resource loading and the script execution. The strict CSP uses a nonce or a hash, and the strict-dynamic directive extends the trust. The HSTS forces the HTTPS, the X-Frame-Options blocks the clickjacking, and the X-Content-Type-Options blocks the MIME-sniffing. The headers are set on the response, and the browser is the enforcer. The headers are not a substitute for the secure code, but they are the layer that limits the damage when the code is breached.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!