Content Security Policy (CSP)
Content Security Policy is delivered via HTTP response header. It defines approved sources of content that the browser may load. It helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks.
A CSP header allows you to define approved sources for content on your site that the browser can load.
Writing CSP Policy
CSP is described using a series of policy directives. The policy should include a default-src directive, which is a fallback for resource types when they don't have policies of their own.
default-src: Serves as a fallback for the other fetch directives.
script-src: Restricts the URLs which can be loaded using script interfaces.
object-src: Specifies valid sources for the <object> and <embed> elements.
style-src: Specifies valid sources for stylesheets.
img-src: Specifies valid sources of images and favicons.
media-src: Specifies valid sources for loading media using the <audio> , <video> and <track> elements.
frame-src: Specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>.
font-src: Specifies valid sources for fonts loaded using @font-face.
connect-src: Restricts the URLs which can be loaded using script interfaces.
form-action: Restricts the URLs which can be used as the target of a form submissions from a given context.
report-uri: Specifies a URI to which the user agent sends reports about policy violation.
You can be as specific or as broad as you like when creating a CSP and fine tune it so that it meets your requirements exactly.
- 'none' blocks the use of this type of resource
- 'self' matches the current origin (but not subdomains)
- 'unsafe-inline' allows the use of inline JS and CSS
- 'unsafe-eval' allows the use of mechanisms like eval()
Content-Security-Policy: default-src https:
This will allow any assets to be loaded over https from any origin.
Content-Security-Policy: default-src example.com
This will allow any assets to be loaded from any origin on example.com using any scheme or port.
Content-Security-Policy: default-src 'self'
This will allow all content to come from the site's own origin.
The report-uri directive specifies a location that the browser should POST a JSON formatted violation report to in the event it has to take action based on the CSP.