Open In App

HTTP headers | Content-Security-Policy

The Content Security Policy response header field is a tool to implement defense in depth mechanism for protection of data from content injection vulnerabilities such as cross-scripting attacks. It provides a policy mechanism that allows developers to detect the flaws present in their application and reduce application privileges. It provides developer control over the application at a granular level to prevent various attacks and maintain content integrity.

Syntax:



Content Security Policy : directive directive-value ; directive directive-value

The above has the directive and directive-value. Multiple policy directives can be used in a line separated by semi-colon.



Directives with Examples:

1. Fetch Directives: These are used to control the point from which a certain resource can be accessed or loaded into the system.

2.Document Directives: These directives control implementation of properties on all documents and worker environments which come under the governance of CSP.

3.Navigation Directives contains form-action, frame-ancestors and navigate-to directives. The form-action directive controls URLs that can be used for form submission. The frame-ancestors directive restricts URLs which can embed the resource using frame, iframe, object, embed, or applet element. The navigate-to directive specifies the URLs to which document can traverse through any method.

4.Reporting Directives contains report-to which specifies the end point to send violation reports. The earlier used report-uri is now deprecated.

Few more Examples:

All the examples in the article have been taken from World Wide Web Consortium’s CSP Level 3 Draft.

Content-Security-Policy: script-src https://cdn.example.com/scripts/; object-src 'none'
Content-Security-Policy: script-src 'self'; report-to csp-reporting-endpoint
Content-Security-Policy: prefetch-src https://example.com/
Content-Security-Policy: worker-src https://example.com/
Content-Security-Policy: navigate-to example.com

Browser Compatibility:

CSP Level 3 is provided partial support from versions Chrome 59+, Firefox 58+, and Edge 79+.
CSP Level 2 is provided full support from versions Chrome 40+, Safari 10+, Edge 76+, and partial support from Firefox 31+ and Edge 15+.
CSP Level 1 is provided full supports from versions Chrome 25+, Firefox 23+, Edge 12+, and Safari 7+.

Article Tags :