patternjavascriptMajor
Subresource Integrity for CDN Scripts
Viewed 0 times
subresource integritysricdnintegrity hashsha384script integritysupply chain
Error Messages
Problem
Scripts loaded from a CDN can be silently modified by the CDN or an intermediary, injecting malicious code into every page that loads the script.
Solution
Add the integrity attribute to script and link tags with the SRI hash of the expected file content. The browser rejects the resource if the hash does not match.
Why
Subresource Integrity allows browsers to verify that a fetched resource has not been tampered with. The hash binds the script to a specific immutable version.
Gotchas
- SRI hashes must be regenerated whenever the CDN resource version changes—pin both the version in the URL and the hash together
- The resource must be served with CORS headers (Access-Control-Allow-Origin: *) for SRI verification to work with cross-origin resources
- Generate SRI hashes using 'openssl dgst -sha384 -binary file.js | openssl base64 -A' or the srihash.com tool
- SRI only protects integrity, not availability—if the CDN goes down, your page loses the resource
Code Snippets
Script tag with SRI integrity attribute
<script
src="https://cdn.example.com/libs/lodash@4.17.21/lodash.min.js"
integrity="sha384-T2yuo9Oe7c3GZ0BHB2uRTFAqDQFuQq3Pn3xQ3A5kJj3ZQ9f3Yy3m8W6n0I7d+A"
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>Revisions (0)
No revisions yet.