Introduction to CSP

What is Content Security Policy ?

Content-Security-Policy, or CSP, is a HTTP header field used by web browsers to control which resources can be loaded by a page. Its main purpose is to protect against various kinds of attacks such as Cross Site Scripting (XSS) attacks, click jacking and other code injection attacks.

Modern websites use a large range of resources: images, fonts, scripts, stylesheets… They have forms, include external content with iframes and use websockets. These features present a large attack surface. CSP allows website developers to control precisely which resources and actions can be used by the web browser.

Example of CSP flow

How to write policies

The main method to declare the policy is to provide it in the Content-Security-Policy header field.

A policy is made of a list of directives controlling which resources can be loaded. The most commonly used are:

Directive Controlled action
connect-src XMLHttpRequest, fetch, websockets…
default-src Default setting for other directives.
font-src Font file loading.
frame-src Frame and Iframe creation.
form-action Form action URLs.
img-src Image file loading.
manifest-src Web Application Manifest loading.
media-src Audio or video file loading.
object-src Plugin content object loading.
prefetch-src Control of links with prefetch or prerender.
script-src Script file loading.
script-src-attr Script attribute loading.
script-src-elem Script element loading.
style-src Stylesheet loading.
style-src-attr Style attribute loading.
style-src-elem Style element loading.
webrtc WebRTC control.
worker-src Web Worker control.

Directives support different kind of values, but you can start with the simplest ones:

  • 'none' to block an entire category of resources.
  • 'self' to only allow the resource if it comes from the same origin as the current page.
  • An URL pattern, for example

A CSP header field for a website using Google Fonts could be:

Content-Security-Policy: default-src 'self'; font-src 'self'; style-src 'self'

With this policy, we make sure that web browsers will only be able to load resources from the website in general, and from Google Fonts for stylesheets and font files.

As a result, if an attacker manages to inject content into the page, for example using a malicious browser extension, they will not be able to trigger external actions.


At this point the benefits of CSP are obvious. While they may seem complex at first, they turn out to be a very powerful tool to help secure a website.

We will explore more complex use cases of CSP in future articles.