What Is Subresource Integrity and How Does SRI Work

Subresource Integrity (SRI) is a web security standard that enables browsers to verify that resources fetched from third-party servers, such as Content Delivery Networks (CDNs), have not been modified or compromised. By allowing developers to provide a cryptographic hash alongside external scripts and stylesheets, SRI ensures that web applications only execute the exact code intended by the developer, effectively preventing supply chain attacks and unauthorized script injection.

The Security Risk of Third-Party CDNs

Web developers frequently load common JavaScript libraries, fonts, and CSS frameworks from public CDNs to optimize loading speeds and reduce bandwidth consumption. However, relying on external servers introduces significant security risks:

How Subresource Integrity Prevents Tampering

Subresource Integrity mitigates these risks by creating a cryptographic contract between the website hosting the HTML and the server providing the external resource.

SRI utilizes the integrity attribute within <script> and <link> elements. This attribute contains a secure cryptographic hash (such as SHA-256, SHA-384, or SHA-512) of the expected file content, encoded in Base64.

The Verification Process

  1. Hash Generation: During development or deployment, the developer generates a cryptographic hash of the unmodified file.
  2. Resource Request: When a user visits the webpage, the browser downloads the external file from the CDN.
  3. Hash Comparison: Before executing the JavaScript or applying the CSS, the browser calculates the hash of the downloaded file using the specified algorithm.
  4. Validation or Rejection:
    • If the calculated hash matches the value in the integrity attribute, the resource is verified as authentic and executes normally.
    • If the hashes do not match—indicating the file was modified, corrupted, or injected with malicious code—the browser immediately blocks execution and logs a network security error in the console.

Implementing SRI

To implement SRI, include the integrity attribute alongside the crossorigin="anonymous" attribute. The crossorigin attribute ensures that Cross-Origin Resource Sharing (CORS) rules are respected, which is required for the browser to check the hash.

<script 
  src="https://cdn.example.com/js/library-3.6.0.min.js" 
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" 
  crossorigin="anonymous">
</script>

Best Practices and Considerations