docs.rodeo

MDN Web Docs mirror

Content-Security-Policy (CSP)

{{HTTPSidebar}} 

The HTTP Content-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 against {{Glossary("cross-site scripting")}}  attacks.

See the Content 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 `{{Glossary("Response header")}}` 
`{{Glossary("Forbidden header name")}}`  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.

All fetch directives may be specified the single value 'none', indicating that the specific resource type should be completely blocked, or as one or more source expression values, indicating valid sources for that resource type. See Fetch 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.

For example:

Document directives

Document directives govern the properties of a document or worker environment to which a policy applies.

Navigation directives govern to which locations a user can navigate or submit a form, for example.

Reporting directives

Reporting directives control the destination URL for CSP violation reports in Content-Security-Policy and {{HTTPHeader("Content-Security-Policy-Report-Only")}} .

Other directives

Deprecated directives

Fetch directive syntax

All fetch directives may be specified as one of the following:

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 string nonce- followed by a {{glossary("Base64", "base64-encoded")}}  string. 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 the nonce attribute of any {{htmlelement("script")}}  or {{htmlelement("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 and unsafe-inline, then the browser ignores unsafe-inline.

See Nonces in the CSP guide for more usage information.

[!NOTE] Nonce source expressions are only applicable to {{htmlelement("script")}}  and {{htmlelement("style")}}  elements.

‘<hash_algorithm>-<hash_value>’

This value consists of a string identifying a hash algorithm, followed by -, followed by a {{glossary("Base64", "base64-encoded")}}  string representing the hash value.

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 the src attribute), then the element must also have the integrity attribute set.

If a directive contains a hash and unsafe-inline, then the browser ignores unsafe-inline.

See Hashes in the CSP guide for more usage information.

[!NOTE] Hash source expressions are only applicable to {{htmlelement("script")}}  and {{htmlelement("style")}}  elements.

<host-source>

The URL or IP address of a {{glossary("host")}}  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:

Wildcards ('*') can be used for subdomains, host address, and port number, indicating that all legal values of each are valid. For example:

Paths that end in / match any path they are a prefix of. For example:

Paths that do not end in / are matched exactly. For example:

<scheme-source>

A scheme, such as https:. The colon is required.

Secure upgrades are allowed, so:

‘self’

Resources of the given type may only be loaded from the same {{glossary("origin")}}  as the document.

Secure upgrades are allowed. For example:

‘unsafe-eval’

By default, if a CSP contains a default-src or a script-src directive, then JavaScript functions which evaluate their arguments as JavaScript are disabled. This includes eval(), the code argument to {{domxref("Window.setTimeout()", "setTimeout()")}} , or the {{jsxref("Function/Function()", "Function()")}}  constructor.

The unsafe-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.

See eval() and similar APIs in the CSP guide for more usage information.

‘wasm-unsafe-eval’

By default, if a CSP contains a default-src or a script-src directive, then a page won’t be allowed to compile WebAssembly using functions like WebAssembly.compileStreaming().

The wasm-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 a default-src or a script-src directive, then inline JavaScript is not allowed to execute. This includes:

Similarly, if a CSP contains default-src or a style-src directive, then inline CSS will not be loaded, including:

The unsafe-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.

See Inline JavaScript in the CSP guide for more usage information.

‘unsafe-hashes’

By default, if a CSP contains a default-src or a script-src directive, then inline event handler attributes like onclick and inline style attributes are not allowed to execute.

The 'unsafe-hashes' expression allows the browser to use hash expressions for inline event handlers and style 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 a style 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 onclick="transferAllMyMoney()">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 a default-src or a script-src directive, then inline JavaScript is not allowed to execute. The 'inline-speculation-rules' allows the browser to load inline <script> elements that have a type attribute of speculationrules.

See the Speculation Rules API for more information.

‘strict-dynamic’

The 'strict-dynamic' keyword makes the trust conferred on a script by a nonce or a hash extend to scripts that this script dynamically loads, for example by creating new <script> tags using {{domxref("Document.createElement()")}}  and then inserting them into the document using {{domxref("Node.appendChild()")}} .

If this keyword is present in a directive, then the following source expression values are all ignored:

See The strict-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 the violation report that the browser generates will contain a {{domxref("CSPViolationReportBody.sample", "sample")}}  property containing the first 40 characters of the blocked resource.

CSP in workers

Workers are in general not governed by the content security policy of the document (or parent worker) that created them. To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which requested the worker 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 does inherit 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, including via the Content-Security-Policy header, the {{HTTPHeader("Content-Security-Policy-Report-Only")}}  header and a {{HTMLElement("meta")}}  element.

You can use the Content-Security-Policy header more than once, as in the example below. Pay special attention to the {{CSP("connect-src")}}  directive here. Even though the second policy would allow the connection, the first policy contains connect-src 'none'. Adding additional policies can only further restrict the capabilities of the protected resource, which means that there will be 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 the unsafe-inline and unsafe-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 {{htmlelement("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 the {{httpheader("Content-Security-Policy-Report-Only")}}  header and the {{CSP("report-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 the {{HTTPHeader("Reporting-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 the {{CSP("report-to")}}  directive.

Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-url/; report-to csp-endpoint

Note that the {{CSP("report-uri")}}  {{deprecated_inline}}  directive is also specified above because report-to is not yet broadly supported by browsers.

See Content Security Policy (CSP) implementation for more examples.

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN