Member-only story
What is CSP (content security policy)?
In this section, we’ll explain what content security policy is, and describe how CSP can be used to mitigate against some common attacks | Portswigger

Content security policy
In this section, we’ll explain what content security policy is, and describe how CSP can be used to mitigate against some common attacks.
What is CSP (content security policy)?
CSP is a browser security mechanism that aims to mitigate XSS and some other attacks. It works by restricting the resources (such as scripts and images) that a page can load and restricting whether a page can be framed by other pages.
To enable CSP, a response needs to include an HTTP response header called Content-Security-Policy
with a value containing the policy. The policy itself consists of one or more directives, separated by semicolons.
Mitigating XSS attacks using CSP
The following directive will only allow scripts to be loaded from the same origin as the page itself:
script-src 'self'
The following directive will only allow scripts to be loaded from a specific domain:
script-src https://scripts.normal-website.com
Care should be taken when allowing scripts from external domains. If there is any way for an attacker to control content that is served from the external domain, then they might be able to deliver an attack. For example, content delivery networks (CDNs) that do not use per-customer URLs, such as ajax.googleapis.com
, should not be trusted, because third parties can get content onto their domains.
In addition to whitelisting specific domains, content security policy also provides two other ways of specifying trusted resources: nonces and hashes:
- The CSP directive can specify a nonce (a random value) and the same value must be used in the tag that loads a script. If the values do not match, then the script will not execute. To be effective as a control, the nonce must be securely generated on each page load and not be guessable by an…