Skip to content

Content Security Policy and security headers: how to reduce risk in the browser

Security headers cost little to deploy and add real protection. See which ones to apply and how to avoid breaking the application.

Reading time
9 min
Published

Security headers are among the most cost-effective defenses for web applications. They tell the browser to behave more restrictively, which weakens entire classes of attack, such as XSS, clickjacking, and connection downgrades. The most important one is the Content Security Policy (CSP), which controls where the browser can load resources from and is the most effective defense in depth against XSS.

The main security headers solve different problems, and some, like CSP, need care so they do not break the application. For each one, we show what it does and how to apply it defensively, with special attention to an effective CSP built with nonces and hashes. The limitations count too: headers give real protection in the browser, but they complement fixes in the application and do not replace them.

Content Security Policy

A CSP defines where scripts, styles, images, and other resources can be loaded from. When it is well configured, it limits the impact of XSS: even if an attacker manages to inject a script, the browser refuses to run it if its source is not allowed. The catch is that a strict CSP can break the application when there are inline scripts or third-party resources that nobody planned for.

That is why you start in report-only mode. In this mode the policy only records violations, without blocking anything, and you find out what the application really loads before tightening the policy step by step. Stay away from broad, unsafe allowances that gut the value of the CSP (letting inline scripts run without restriction is the classic example), and prefer specific policies for each resource type.

Building an effective CSP with nonces and hashes

Broadly allowing inline scripts is exactly what weakens the policy against XSS, and a strong CSP does not need it. Two techniques authorize the legitimate inline scripts without opening the door to everything else. A nonce is a random value, generated for each response, that the server puts in the header and also in the tag of the legitimate script. The browser only runs an inline script that carries the correct nonce. A hash, in turn, authorizes one specific inline script by its cryptographic digest, which is useful when the content is fixed.

Example of a nonce-based CSP, hardened directive by directive
Content-Security-Policy:  default-src 'self';  script-src 'self' 'nonce-RANDOM_VALUE';  object-src 'none';  base-uri 'self';  frame-ancestors 'none';  report-to csp-endpoint

Look at a few directives in the example. Setting object-src to none blocks legacy plugins, which only add attack surface. A restricted base-uri keeps an attacker from changing the base used to resolve the page's URLs. And frame-ancestors replaces the old X-Frame-Options header in controlling who can frame the page. To receive violation reports in a structured way, use the report-to directive together with an endpoint that collects the events. That real data is what should guide the hardening.

The other essential headers

Besides CSP, a few headers raise the security baseline with very little effort. HSTS forces HTTPS and prevents connection downgrades. X-Content-Type-Options stops the browser from guessing the content type. Against clickjacking, use the CSP frame-ancestors directive (or X-Frame-Options in older browsers). Referrer-Policy controls how much of the URL leaks through the referrer, and Permissions-Policy restricts browser features such as the camera and geolocation.

A set of headers that raises the security baseline
Strict-Transport-Security: max-age=63072000; includeSubDomains; preloadX-Content-Type-Options: nosniffReferrer-Policy: strict-origin-when-cross-originPermissions-Policy: geolocation=(), camera=(), microphone=()

With HSTS, be careful about scope. The subdomain directive (includeSubDomains) applies the policy to all of them, and getting into the browsers' preload list is hard to undo. Enable these two only when you are sure every subdomain serves HTTPS. In production you want a generous max-age, but during validation start with a smaller value. That way, if a forgotten subdomain still depends on HTTP, it does not stay locked out for long.

  • CSP with a nonce or hash, to control where resources come from and mitigate XSS in depth
  • HSTS, which forces HTTPS and prevents downgrades (careful with subdomains and preload)
  • X-Content-Type-Options set to nosniff, against content type sniffing
  • frame-ancestors, or X-Frame-Options in older browsers, against clickjacking
  • Referrer-Policy to limit how much of the URL leaks through the referrer
  • Permissions-Policy to restrict sensitive browser features

Secure cookies and origin isolation

Response headers do not stop at CSP. Session cookies need security attributes of their own. Secure makes the cookie travel only over HTTPS. HttpOnly keeps JavaScript from reading it, so an XSS loses much of its value to the attacker. SameSite limits when the cookie is sent on cross-site requests, which helps against CSRF. A session cookie without these attributes is an easy target, and the mistake is common.

Security attributes on a session cookie
Set-Cookie: session=VALUE; Secure; HttpOnly; SameSite=Lax; Path=/

In applications that handle sensitive data or use advanced browser features, cross-origin isolation adds a layer against side-channel attacks. The Cross-Origin-Opener-Policy and Cross-Origin-Resource-Policy headers separate your page's context from windows and resources that belong to other origins. They need testing, because they can affect legitimate integrations, but they strengthen isolation exactly where it makes a difference.

Where to apply headers, and their limits

You can apply the headers in the application itself or at the edge, for example in CloudFront or Cloudflare. The edge makes it easier to standardize across several services and keeps the configuration consistent. The problem is headers that depend on a per-response value, like the CSP nonce: those have to be generated by the application. So the policy sometimes lives in both places, with a standard baseline at the edge and the dynamic part in the application.

Keep in mind that a header is defense in depth. It reduces the impact of a flaw, but the flaw is still there: an application vulnerable to XSS stays vulnerable, and the CSP only makes exploitation harder. Combine the headers with code fixes and testing. And review the policy whenever you add a third-party resource, because each new external script calls for a decision about your CSP.

Practical checklist

  • Define the CSP and start in report-only mode
  • Authorize legitimate inline scripts with a nonce or hash instead of allowing inline code broadly
  • Harden the policy with object-src none, base-uri, and frame-ancestors
  • Set up an endpoint to receive CSP violation reports
  • Analyze the violations and tighten the CSP gradually
  • Enable HSTS, taking care with subdomains and preload
  • Apply X-Content-Type-Options with nosniff
  • Set a Referrer-Policy and a Permissions-Policy that fit the site
  • Mark session cookies with Secure, HttpOnly, and SameSite
  • Evaluate cross-origin isolation for sensitive applications
  • Standardize headers at the edge and generate the dynamic part in the application
  • Treat headers as defense in depth and fix the flaw in the code

Best practices

  • Start the CSP in report-only mode and tighten it based on what the reports show
  • Use nonces and hashes instead of broadly allowing inline scripts
  • Standardize headers at the edge whenever possible
  • Protect session cookies with Secure, HttpOnly, and SameSite
  • Use headers alongside fixes in the application
  • Review the headers whenever a third-party resource is added
  • Test how the site behaves after each round of hardening

Common mistakes

A CSP that broadly allows inline scripts
The policy is there, but in practice it does not protect against XSS.
Deploying a strict CSP right away, without report-only mode
Legitimate resources break, and the team ends up loosening everything.
HSTS with preload before every subdomain is on HTTPS
Any subdomain that still depends on HTTP becomes unreachable, and reverting the preload is hard.
Session cookies without Secure, HttpOnly, and SameSite
The session can be stolen by a script or sent on cross-site requests where it does not belong.
Treating headers as a vulnerability fix
The flaw stays in the code; the headers only make exploitation harder.
Inconsistent headers across services
Without standardization, some endpoints are left unprotected.

Authorship and review

Cesar Gargiulo

CEO and founder of GUARDIASEC. Technical and editorial lead for the content published in this library.

Published on . Found a technical error? Write to [email protected] and we will correct it and keep a record of the change.

Frequently asked questions

Does CSP eliminate the risk of XSS?
No, but it reduces the impact a lot. CSP is defense in depth: even if an XSS payload gets injected, the browser refuses to run scripts from sources that are not allowed, and exploitation becomes harder. You still need to fix the flaw in the application. CSP is a strong layer, but what actually solves XSS is secure code.
Why start the CSP in report-only mode?
Because a strict CSP can block legitimate resources the application loads, especially inline scripts and third-party content. In report-only mode, violations are logged without being blocked, and you map what the application really uses before tightening anything. Teams that push a strict policy straight to production usually break the application, and the reaction ends up being to loosen everything.
What is the difference between a nonce and a hash in CSP?
A nonce is a random value, generated for each response, that the server puts in the header and in the tag of the legitimate script. The browser only runs an inline script that carries the right nonce, which is why a nonce suits content that changes. A hash authorizes one specific inline script by its cryptographic digest and works for fixed content. Both let you avoid broadly allowing inline scripts, which is what weakens the policy against XSS.
Where should I apply security headers?
In the application or at the edge, for example in CloudFront or Cloudflare. The edge makes it easier to standardize headers across several services, but values that change with every response, like the CSP nonce, have to come from the application. In practice, the most reliable setup is usually a standard baseline at the edge plus the dynamic part generated by the application.
Is HSTS with preload always recommended?
Only with care. Being on the browsers' preload list forces HTTPS for the domain and its subdomains, and it is hard to reverse. Enable preload and the subdomain directive only when you are sure every subdomain serves HTTPS. During validation, use a smaller max-age and raise it later, so a forgotten subdomain that still depends on HTTP does not get locked out.
Do security headers replace a penetration test?
No. Headers are defense in depth: they reduce the impact of certain flaws, but they do not fix the application's vulnerabilities. A penetration test assesses how the application really behaves and finds the flaws that headers only mitigate. The best approach is to combine well-configured headers with code fixes and regular security testing.

When to bring in specialist help

Building an effective CSP that does not break the application, and standardizing the headers, falls under two GUARDIASEC services: application security, and WAF and edge protection. We look at how the application behaves in the browser and adjust the configuration based on what we find.