Introduction to HTTP and Content Security Policy (CSP)

introduction to http and content security policy
10 November 2024

The discussion of Content Security Policy (CSP) is one of the important and vital topics in the web world today. In simple terms, CSP is designed to enhance the security of web pages by restricting the sources that content can be loaded from, which is intended to mitigate potential risks associated with the loading of content from untrusted sources.

Suppose you have a website and you want to ensure that users only use resources that you have authorized. CSP gives you the ability to allow only certain domains and resources that have been trusted, enhancing security and trust in your pages.

The main application of CSP is the prevention of injection attacks, such as Cross-Site Scripting (XSS). By defining a policy that specifies which resources can be loaded on your pages, the chances of unauthorized access can be significantly reduced, thus preventing harmful injections from rogue agents.

CSP is very simple to define and is implemented through an HTTP header called Content-Security-Policy on the responses of the page. This header includes different rules that the browser must comply with, including resources that are allowed to be loaded such as images, scripts, styles, and more.

Examples of Content Security Policies

Below are examples of CSP definitions that only allow scripts and styles from trusted domain example.com:

Content-Security-Policy: script-src 'self' https://example.com; style-src 'self' https://example.com;

These settings inform the browser to allow only script and style resources from the specified domains. Anything else will be blocked.

Code Line Details

Content-Security-Policy:
This declaration specifies the beginning of the content security policy.
script-src 'self' https://example.com;
This part specifies that script resources must be loaded either from the current domain ('self') or from https://example.com.
style-src 'self' https://example.com;
This section indicates that styles must be loaded only from the current domain ('self') or from https://example.com.

FAQ

?

How can CSP help secure a website?

?

Can CSP act as a fallback?

?

Can CSP be defined differently for different domains?