Content-Security-Policy (CSP) header
BaselineWidely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since August 2016.
* Some parts of this feature may have varying levels of support.
The HTTPContent-Security-Policy
response header allows website administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints.This helps guard againstcross-site scripting attacks.
See theContent Security Policy (CSP) guide for details about how a CSP is delivered to the browser, what it looks like, along with use cases and deployment strategies.
Header type | Response header |
---|---|
Forbidden request header | no |
Syntax
Content-Security-Policy: <policy-directive>; <policy-directive>
where<policy-directive>
consists of:<directive> <value>
with no internal punctuation.
Directives
Fetch directives
Fetch directives control the locations from which certain resource types may be loaded.
child-src
Defines the valid sources forweb workers and nested browsing contexts loaded using elements such as
<frame>
and<iframe>
.Fallback for
frame-src
andworker-src
.connect-src
Restricts the URLs which can be loaded using script interfaces.
default-src
Serves as a fallback for the otherfetch directives.
Fallback for all other fetch directives.
fenced-frame-src
ExperimentalSpecifies valid sources for nested browsing contexts loaded into
<fencedframe>
elements.font-src
Specifies valid sources for fonts loaded using
@font-face
.frame-src
Specifies valid sources for nested browsing contexts loaded into elements such as
<frame>
and<iframe>
.img-src
Specifies valid sources of images and favicons.
manifest-src
Specifies valid sources of application manifest files.
media-src
Specifies valid sources for loading media using the
<audio>
,<video>
and<track>
elements.object-src
Specifies valid sources for the
<object>
and<embed>
elements.prefetch-src
DeprecatedNon-standardSpecifies valid sources to be prefetched or prerendered.
script-src
Specifies valid sources for JavaScript and WebAssembly resources.
Fallback for
script-src-elem
andscript-src-attr
.script-src-elem
Specifies valid sources for JavaScript
<script>
elements.script-src-attr
Specifies valid sources for JavaScript inline event handlers.
style-src
Specifies valid sources for stylesheets.
Fallback for
style-src-elem
andstyle-src-attr
.style-src-elem
Specifies valid sources for stylesheets
<style>
elements and<link>
elements withrel="stylesheet"
.style-src-attr
Specifies valid sources for inline styles applied to individual DOM elements.
worker-src
Specifies valid sources for
Worker
,SharedWorker
, orServiceWorker
scripts.
All fetch directives may be specified the single value'none'
, indicating that the specific resource type should be completely blocked, or as one or moresource expression values, indicating valid sources for that resource type. SeeFetch directive syntax for more details.
Fallbacks
Some fetch directives function as fallbacks for other more granular directives. This means that if the more granular directive is not specified, then the fallback is used to provide a policy for that resource type.
default-src
is a fallback for all other fetch directives.script-src
is a fallback forscript-src-attr
andscript-src-elem
.style-src
is a fallback forstyle-src-attr
andstyle-src-elem
.child-src
is a fallback forframe-src
andworker-src
.
For example:
- If
img-src
is omitted butdefault-src
is included, then the policy defined bydefault-src
will be applied to images. - If
script-src-elem
is omitted butscript-src
is included, then the policy defined byscript-src
will be applied to<script>
elements. - If
script-src-elem
andscript-src
are both omitted, butdefault-src
is included, then the policy defined bydefault-src
will be applied to<script>
elements.
Document directives
Navigation directives
Navigation directives govern to which locations a user can navigate or submit a form,for example.
form-action
Restricts the URLs which can be used as the target of a form submissions from agiven context.
frame-ancestors
Specifies valid parents that may embed a page using
<frame>
,<iframe>
,<object>
, or<embed>
.
Reporting directives
Reporting directives control the destination URL for CSP violation reports inContent-Security-Policy
andContent-Security-Policy-Report-Only
.
report-to
Provides the browser with a token identifying the reporting endpoint or group of endpoints to send CSP violation information to.The endpoints that the token represents are provided through other HTTP headers, such as
Reporting-Endpoints
andReport-To
Deprecated.Warning:This directive is intended to replace
report-uri
; in browsers that supportreport-to
, thereport-uri
directive is ignored.However untilreport-to
is broadly supported you should specify both headers as shown (whereendpoint_name
is the name of a separately provided endpoint):httpContent-Security-Policy: …; report-uri https://endpoint.example.com; report-to endpoint_name
Other directives
require-trusted-types-for
EnforcesTrusted Types at the DOM XSS injection sinks.
trusted-types
Used to specify an allowlist ofTrusted Types policies.Trusted Types allows applications to lock down DOM XSS injection sinks to only accept non-spoofable, typed values in place of strings.
upgrade-insecure-requests
Instructs user agents to treat all of a site's insecure URLs (those served overHTTP) as though they have been replaced with secure URLs (those served over HTTPS).This directive is intended for websites with large numbers of insecure legacy URLsthat need to be rewritten.
Deprecated directives
block-all-mixed-content
DeprecatedPrevents loading any assets using HTTP when the page is loaded using HTTPS.
report-uri
DeprecatedProvides the browser with a URL where CSP violation reports should be sent.This has been superseded by the
report-to
directive.
Fetch directive syntax
All fetch directives may be specified as one of the following:
- the single value
'none'
, indicating that the specific resource type should be completely blocked - one or moresource expression values, indicating valid sources for that resource type.
Each source expression takes one of the forms listed below. Note that not all forms are applicable to all fetch directives: see the documentation for each fetch directive to find out which forms are applicable to it.
The<host-source>
and<scheme-source>
formats must be unquoted, and all other formats must be enclosed in single quotes.
'nonce-<nonce_value>'
This value consists of the stringnonce-
followed by a nonce value. The nonce value may use any of the characters fromBase64 orURL-safe Base64.
This string is a random value that the server generates for every HTTP response. For example:
'nonce-416d1177-4d12-4e3b-b7c9-f6c409789fb8'
The server can then include the same value as the value of thenonce
attribute of any<script>
or<style>
resources that they intend to load from the document.
The browser compares the value from the CSP directive against the value in the element attribute, and loads the resource only if they match.
If a directive contains a nonce andunsafe-inline
, then the browser ignoresunsafe-inline
.
SeeNonces in the CSP guide for more usage information.
'<hash_algorithm>-<hash_value>'
This value consists of a string identifying a hash algorithm, followed by-
, followed by a hash value. The hash value may use any of the characters fromBase64 orURL-safe Base64.
- The hash algorithm identifier must be one of
sha256
,sha384
, orsha512
. - The hash value is the base64-encodedhash of a
<script>
or<style>
resource, calculated using one of the following hash functions: SHA-256, SHA-384, or SHA-512.
For example:
'sha256-cd9827ad...'
When the browser receives the document, it hashes the contents of any<script>
and<style>
elements, compares the result with any hashes in the CSP directive, and loads the resource only if there is a match.
If the element loads an external resource (for example, using thesrc
attribute), then the element must also have theintegrity
attribute set.
If a directive contains a hash andunsafe-inline
, then the browser ignoresunsafe-inline
.
SeeHashes in the CSP guide for more usage information.
<host-source>
TheURL or IP address of ahost that is a valid source for the resource.
The scheme, port number, and path are optional.
If the scheme is omitted, the scheme of the document's origin is used.
When matching schemes, secure upgrades are allowed. For example:
http://example.com
will also permit resources fromhttps://example.com
ws://example.org
will also permit resources fromwss://example.org
.
Wildcards ('*'
) can be used for subdomains, host address, and port number, indicating that all legal values of each are valid. For example:
http://*.example.com
permits resources from any subdomain ofexample.com
, over HTTP or HTTPS.
Paths that end in/
match any path they are a prefix of. For example:
example.com/api/
will permit resources fromexample.com/api/users/new
.
Paths that do not end in/
are matched exactly. For example:
https://example.com/file.js
permits resources fromhttps://example.com/file.js
but nothttps://example.com/file.js/file2.js
.
<scheme-source>
Ascheme, such ashttps:
. The colon is required.
Secure upgrades are allowed, so:
http:
will also permit resources loaded using HTTPSws:
will also permit resources loaded using WSS.
'self'
Resources of the given type may only be loaded from the sameorigin as the document.
Secure upgrades are allowed. For example:
- If the document is served from
http://example.com
, then a CSP of'self'
will also permit resources fromhttps://example.com
. - If the document is served from
ws://example.org
, then a CSP of'self'
will also permit resources fromwss://example.org
.
'unsafe-eval'
By default, if a CSP contains adefault-src
or ascript-src
directive, then JavaScript functions which evaluate their arguments as JavaScript are disabled. This includeseval()
, thecode
argument tosetTimeout()
, or theFunction()
constructor.
Theunsafe-eval
keyword can be used to undo this protection, allowing dynamic evaluation of strings as JavaScript.
Warning:Developers should avoid'unsafe-eval'
, because it defeats much of the purpose of having a CSP.
Seeeval()
and similar APIs in the CSP guide for more usage information.
'wasm-unsafe-eval'
By default, if a CSP contains adefault-src
or ascript-src
directive, then a page won't be allowed to compile WebAssembly using functions likeWebAssembly.compileStreaming()
.
Thewasm-unsafe-eval
keyword can be used to undo this protection. This is a much safer alternative to'unsafe-eval'
, since it does not enable general evaluation of JavaScript.
'unsafe-inline'
By default, if a CSP contains adefault-src
or ascript-src
directive, then inline JavaScript is not allowed to execute. This includes:
- inline
<script>
tags - inline event handler attributes
#"/en-US/docs/Web/API/HTMLElement/style" title="style">
style
attributes.
Theunsafe-inline
keyword can be used to undo this protection, allowing all these forms to be loaded.
Warning:Developers should avoid'unsafe-inline'
, because it defeats much of the purpose of having a CSP.
SeeInline JavaScript in the CSP guide for more usage information.
'unsafe-hashes'
By default, if a CSP contains adefault-src
or ascript-src
directive, then inline event handler attributes likeonclick
and inlinestyle
attributes are not allowed to execute.
The'unsafe-hashes'
expression allows the browser to usehash expressions for inline event handlers andstyle
attributes. For example, a CSP might contain a directive like this:
script-src 'unsafe-hashes' 'sha256-cd9827ad...'
If the hash value matches the hash of an inline event handler attribute value or of astyle
attribute value, then the code will be allowed to execute.
Warning:The'unsafe-hashes'
value is unsafe.
In particular, it enables an attack in which the content of the inline event handler attribute is injected into the document as an inline<script>
element. Suppose the inline event handler is:
<button>Transfer all my money</button>
If an attacker can inject an inline<script>
element containing this code, the CSP will allow it to execute automatically.
However,'unsafe-hashes'
is much safer than'unsafe-inline'
.
'inline-speculation-rules'
By default, if a CSP contains adefault-src
or ascript-src
directive, then inline JavaScript is not allowed to execute. The'inline-speculation-rules'
allows the browser to load inline<script>
elements that have atype
attribute ofspeculationrules
.
See theSpeculation Rules API for more information.
'strict-dynamic'
The'strict-dynamic'
keyword makes the trust conferred on a script by anonce or ahash extend to scripts that this script dynamically loads, for example by creating new<script>
tags usingDocument.createElement()
and then inserting them into the document usingNode.appendChild()
.
If this keyword is present in a directive, then the following source expression values are all ignored:
SeeThestrict-dynamic
keyword in the CSP guide for more usage information.
'report-sample'
If this expression is included in a directive controlling scripts or styles, and the directive causes the browser to block any inline scripts, inline styles, or event handler attributes, then theviolation report that the browser generates will contain asample
property containing the first 40 characters of the blocked resource.
CSP in workers
Workers are in generalnot governedby the content security policy of the document (or parent worker) that created them. Tospecify a content security policy for the worker, set aContent-Security-Policy
response header for the request which requested theworker script itself.
The exception to this is if the worker script's origin is a globally unique identifier(for example, if its URL has a scheme of data or blob). In this case, the worker doesinherit the content security policy of the document or worker that created it.
Multiple content security policies
The CSP mechanism allows multiple policies being specified for a resource, includingvia theContent-Security-Policy
header, theContent-Security-Policy-Report-Only
header and a<meta>
element.
You can use theContent-Security-Policy
header more than once, as in theexample below. Pay special attention to theconnect-src
directive here. Eventhough the second policy would allow the connection, the first policy containsconnect-src 'none'
. Adding additional policiescan only furtherrestrict the capabilities of the protected resource, which means that there willbe no connection allowed and, as the strictest policy,connect-src 'none'
is enforced.
Content-Security-Policy: default-src 'self' http://example.com; connect-src 'none';Content-Security-Policy: connect-src http://example.com/; script-src http://example.com/
Examples
Disable unsafe inline code and only allow HTTPS resources
This HTTP header sets the default policy to only allow resource loading (images, fonts, scripts, etc.) over HTTPS.Because theunsafe-inline
andunsafe-eval
directives are not set, inline scripts will be blocked.
Content-Security-Policy: default-src https:
The same restrictions can be applied using the HTML<meta>
element.
<meta http-equiv="Content-Security-Policy" content="default-src https:" />
Allow inline code and HTTPS resources, but disable plugins
This policy could be used on a pre-existing site that uses too much inline code to fix, to ensure resources are loaded only over HTTPS and disable plugins:
Content-Security-Policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
Report but don't enforce violations when testing
This example sets the same restrictions as the previous example, but using theContent-Security-Policy-Report-Only
header and thereport-to
directive.This approach is used during testing to report violations but not block code from executing.
Endpoints (URLs) to send reports to are defined using theReporting-Endpoints
HTTP response header.
Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"
A particular endpoint is then selected as the report target in the CSP policy using thereport-to
directive.
Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-url/; report-to csp-endpoint
Note that thereport-uri
Deprecated directive is also specified above becausereport-to
is not yet broadly supported by browsers.
SeeContent Security Policy (CSP) implementation for more examples.
Specifications
Specification |
---|
Content Security Policy Level 3 # csp-header |
Browser compatibility
See also
Content-Security-Policy-Report-Only
- Learn about: Content Security Policy
- Content Security in WebExtensions
- Adopting a strict policy
- CSP Evaluator - Evaluate yourContent Security Policy