SRI Combined with Content Security Policy
Combine Subresource Integrity with Content Security Policy (CSP) for defense-in-depth security. Learn how to require SRI via CSP headers and maximize browser protection.
Detailed Explanation
SRI + Content Security Policy (CSP): Defense in Depth
SRI and CSP are complementary security mechanisms. While SRI verifies the content of loaded resources, CSP controls where resources can be loaded from. Together, they provide a robust defense against script injection and supply-chain attacks.
Requiring SRI via CSP
CSP has a dedicated directive that requires SRI for all scripts and styles:
Content-Security-Policy: require-sri-for script style
With this header, the browser will block any <script> or <link rel="stylesheet"> that does not include an integrity attribute — even for same-origin resources.
Note: The require-sri-for directive was part of the CSP Level 3 draft but has been deprecated in some browsers. Check current browser support before relying on it.
CSP + SRI Together
A typical secure configuration combines both:
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.example.com;
style-src 'self' https://cdn.example.com;
<script
src="https://cdn.example.com/lib.js"
integrity="sha384-..."
crossorigin="anonymous"
></script>
This configuration:
- CSP ensures scripts can only load from your domain and the approved CDN
- SRI ensures the CDN-loaded scripts have not been modified
- Together, they prevent both unauthorized sources and tampered content
What Each Layer Protects Against
| Threat | CSP | SRI | Both |
|---|---|---|---|
| Script from unknown domain | Blocked | Not checked | Blocked |
| Tampered file on approved CDN | Allowed | Blocked | Blocked |
| Inline script injection (XSS) | Blocked (no 'unsafe-inline') | Not applicable | Blocked |
| Modified same-origin script | Allowed | Blocked | Blocked |
CSP Reporting and SRI
CSP's reporting mechanism (report-uri or report-to) will report violations for scripts blocked by CSP policy. SRI failures are reported separately as error events on the element. For comprehensive monitoring, implement both CSP reporting and SRI error event listeners.
Implementation Strategy
- Start with CSP in report-only mode to identify all loaded resources
- Add SRI hashes to all external resources
- Tighten CSP to allow only known domains
- Consider
require-sri-forif browser support is sufficient - Monitor both CSP reports and SRI error events in production
Use Case
Combining SRI with CSP is the gold standard for web application security. This approach is required by security audits in fintech, healthtech, and government applications. It is also recommended by OWASP as part of their secure headers configuration. Organizations seeking SOC 2 Type II compliance often implement both mechanisms together.