JavaScript > Security > Security Best Practices > Content Security Policy (CSP)
Content Security Policy: Inline Script Protection
This snippet demonstrates how to use Content Security Policy (CSP) to prevent the execution of inline JavaScript, mitigating Cross-Site Scripting (XSS) attacks.
CSP Header Configuration
This CSP header is set on the server-side. It instructs the browser to only allow scripts from the same origin ('self'). Any inline scripts, or scripts from a different domain, will be blocked. The `default-src 'self'` part defines a fallback policy for all resource types when a specific directive isn't set.
Content-Security-Policy: default-src 'self'; script-src 'self'
Example HTML with Inline Script (Blocked)
When this HTML is served with the CSP header defined above, the inline script `alert('This inline script will be blocked by CSP.');` will be blocked by the browser. The browser's developer console will show a CSP error message indicating the violation. You may need to adjust the CSP to see the blocking in action and confirm how CSP works.
<!DOCTYPE html>
<html>
<head>
<title>CSP Demo</title>
</head>
<body>
<h1>CSP Inline Script Demo</h1>
<script>
alert('This inline script will be blocked by CSP.');
</script>
</body>
</html>
External Script (Allowed)
Place this JavaScript code in a file named `external-script.js` and host it on the same domain as the HTML file.
// external-script.js
alert('This external script is allowed by CSP.');
Example HTML with External Script (Allowed)
This HTML file loads the `external-script.js` file, which is served from the same origin. Since the `script-src` directive in the CSP allows scripts from the same origin ('self'), this script will execute without any issues.
<!DOCTYPE html>
<html>
<head>
<title>CSP Demo</title>
</head>
<body>
<h1>CSP External Script Demo</h1>
<script src="external-script.js"></script>
</body>
</html>
Concepts Behind the Snippet
CSP is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS). XSS attacks are enabled when the web server allows user-supplied data to be included on the page without proper validation or escaping. CSP makes it more difficult for an attacker to inject malicious scripts into your website. By explicitly whitelisting the sources of content the browser should be allowed to load, you can significantly reduce the risk of XSS attacks. The key is to specify the `Content-Security-Policy` HTTP header on your web server.
Real-Life Use Case
Consider a social media platform where users can post comments. Without CSP, a malicious user could inject JavaScript code into a comment. This code could steal other users' cookies or perform actions on their behalf. By implementing CSP, the platform can prevent the execution of such injected scripts, as they would be considered inline or from an untrusted source. The platform admin sets CSP on the server to block execution from untrusted sources.
Best Practices
Interview Tip
When discussing CSP in an interview, emphasize your understanding of how it mitigates XSS attacks and your experience in configuring and testing CSP policies. Be prepared to discuss the various directives (e.g., `script-src`, `style-src`, `img-src`) and the trade-offs involved in choosing a restrictive vs. permissive policy. Mentioning the importance of monitoring CSP violations demonstrates a proactive approach to security.
When to Use CSP
CSP should be used on any website where security is a concern, particularly websites that handle sensitive user data or allow user-generated content. It's a fundamental security measure that should be implemented as part of a comprehensive security strategy. Even on static websites, CSP can provide a defense-in-depth against certain types of attacks.
Alternatives
While CSP is the most robust way to control resources, other methods to improve security include:
CSP complements these techniques but should not be considered a replacement for them.
Pros
Cons
FAQ
-
What is a nonce in CSP?
A nonce is a cryptographically random number used to whitelist specific inline scripts. The server generates a unique nonce for each request and includes it in both the CSP header and the `nonce` attribute of the script tag. This ensures that only scripts with the correct nonce are allowed to execute. -
How do I report CSP violations?
Use the `report-uri` or `report-to` directives in your CSP header to specify an endpoint where the browser should send reports of CSP violations. The `report-uri` directive is deprecated, and `report-to` is the preferred method. You'll need to configure a server-side script to receive and process these reports.