Subresource Integrity (SRI) is a security feature that helps browsers ensure that files they download (like JavaScript or CSS from a CDN) haven’t been tampered with. It does this by allowing the developer to include a cryptographic hash, which the browser checks to verify the file’s integrity.
If a content delivery network (CDN) is compromised and someone alters the JavaScript or CSS files hosted there, every website using those files could be at risk. For instance, if a JavaScript file loaded from a CDN is modified by an attacker, it could lead to dangerous outcomes like stealing user data, altering content, or even taking down a site (denial-of-service attacks).
By using SRI, you can "lock" a resource to a specific version using a cryptographic hash. This hash, which you provide in the integrity
attribute, ensures that if the file changes, the browser won’t load it.
SRI is essential when loading external JavaScript or CSS resources and should always be used with HTTPS. If the content has been altered in any way, browsers that support SRI will block the file from loading.
Additionally, for SRI to work, CDNs must allow cross-origin access by setting the Access-Control-Allow-Origin
header (CORS).
<script src="https://code.jquery.com/jquery-2.1.4.min.js" integrity="sha384-R4/ztc4ZlRqWjqIuvf6RX5yb/v90qNGx6fS48N0tRxiGkqveZETq72KgDVJCp2TC" crossorigin="anonymous"></script>
Loading AngularJS with SRI:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js" integrity="sha384-r1y8TJcloKTvouxnYsi4PJAx+nHNr90ibsEn3zznzDzWBN9X3o3kbHLSgcIPtzAp" crossorigin="anonymous"></script>
Generate your own SRI hash:
$ curl -s https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js | \ openssl dgst -sha384 -binary | \ openssl base64 -A
SRI helps protect your site by ensuring that external resources haven't been maliciously altered.