Understanding SRI: Subresource Integrity (and how to use it with ASP.NET)

Posted: (EET/GMT+2)

 

Subresource Integrity (SRI) is a W3C standard that helps browsers verify that scripts or styles loaded from a CDN (Content Delivery Network) haven't been modified. It adds a small hash attribute to your <script> or <link> tag so the browser can check the file before processing/running it.

Here's a simple example with jQuery:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
     integrity="sha384-tsQFQPbyzQJ4Aq4N2Y7g6a5yFfWm5T3e5VJr5xRr0HgZVd5GeUXrXe3G5UpiJY4/"
     crossorigin="anonymous"></script>

The integrity attribute contains a base64-encoded hash (often SHA-384). If the CDN file is altered, the hash no longer matches and the browser refuses to execute it. It's a simple and effective defense against supply-chain tampering if you host files outside your own application.

To use SRI in your ASP.NET or ASP.NET Core layouts, just include the integrity and crossorigin attributes in your bundle references. For example, in a CSHTML/Razor view:

<environment include="Production">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.1.0/dist/js/bootstrap.min.js"
            integrity="sha384-smHYKdLADwkXOn1sDQK0rUtKQNPF5bDnpF+z5qU2wzP5K3phQOeW5FQ5Y1yp3Z5m"
            crossorigin="anonymous"></script>
</environment>

If you generate your bundles locally, you can compute hashes yourself using the openssl Linux command or PowerShell:

# PowerShell example
Get-FileHash .\bootstrap.min.js -Algorithm SHA384 |
  ForEach-Object { [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($_.Hash)) }

Browser support for SRI is already very good. The Can I Use site already reports wide adoption across modern browsers, so it's safe to use. SRI is one of those web security standards that's easy to adopt and doesn't require any server-side configuration.

Even though ASP.NET and ASP.NET Core applications often serve static files locally, many sites reference shared CDNs for libraries such as jQuery or Bootstrap. Adding an integrity attribute to those links costs almost nothing and improves your site's overall trustworthiness.