How Content Security Policy Works
How Content Security Policy Works
CSP operates through HTTP response headers or HTML meta tags that instruct the browser about content restrictions for a particular page. When a browser receives these instructions, it enforces them throughout the page lifecycle, blocking any attempts to load or execute content that violates the policy. This enforcement happens at a fundamental level within the browser's security model, making it extremely difficult for attackers to bypass.
The basic CSP header structure follows this pattern:
Content-Security-Policy: directive-name source-list; another-directive source-list
Here's a simple example that demonstrates CSP in action:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.example.com">
<title>CSP Protected Page</title>
</head>
<body>
<!-- This script will load successfully -->
<script src="https://trusted-cdn.example.com/script.js"></script>
<!-- This script will be blocked by CSP -->
<script src="https://evil-site.com/malicious.js"></script>
<!-- This inline script will also be blocked -->
<script>
alert('This will not execute!');
</script>
</body>
</html>
In this example, the CSP policy allows scripts only from the same origin ('self') and from the trusted CDN. Any attempt to load scripts from other sources or execute inline scripts will be blocked by the browser.