Content Security Policy (CSP) is an additional security layer that helps detect and mitigate certain types of attacks, such as cross-site scripting (XSS) and data injection attacks. CSP enhances website security primarily by specifying which types of resources (e.g., JavaScript, CSS, HTML) are trusted for execution.
CSP is implemented by servers sending specific HTTP headers to the browser. This header, known as Content-Security-Policy, defines how the browser should handle the page's policies and which external resources can be loaded and executed.
For example, if a webpage sets the following CSP policy:
plaintextContent-Security-Policy: default-src 'self'; script-src 'self' https://apis.example.com
This policy instructs the browser:
- By default, only resources from the same origin (i.e., the same domain) are allowed to be loaded and executed.
- For scripts (such as JavaScript), in addition to allowing scripts from the same origin, scripts can also be loaded from the specified
https://apis.example.com.
In this way, if an attacker attempts to inject malicious scripts into the page, these scripts will be blocked from execution because their source does not match the allowed sources defined in CSP. Using CSP can significantly enhance application security, particularly in preventing XSS attacks. However, configuring CSP requires a fine balance; overly strict policies may break website functionality, while overly permissive policies may weaken security. Therefore, when implementing CSP, it is typically necessary to adjust the policies based on the specific requirements of the application.