Securing your CDN: Why and how should you use SRI


Let’s take a look at how SRI works. Imagine that you want to include jQuery on your site. Here’s the SRI code that you can use:

<script
  src="https://code.jquery.com/jquery-3.7.0.slim.min.js"
  integrity="sha256-tG5mcZUtJsZvyKAxYLVXrmjKBVLd6VpVccqz/r4ypFE="
  crossorigin="anonymous"
></script>

And for CSS, it is pretty similar:

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/picnic"
  integrity="sha384-v1z6igsPTyRDbi5o+gRfebiF45laQTyfvucMlEmzfyalawh17iTvBbICU08I7ksb"
  crossorigin="anonymous"
/>

As you’ll notice, there are two new attributes compared to a normal <script> or <link> element. These are crossorigin and integrity.

The crossorigin attribute is the easier one to explain. This attribute tells your browser to anonymously request the resource from the server. No username, password, or other identifying information is sent to the server.

The integrity attribute is slightly more complicated. It contains a mathematical representation – called a “hash” – of the code you are requesting. The first part sha384 says that the algorithm being used is SHA384. This tells the browser to use that algorithm to analyze the code being requested. That will generate a long string of characters. If the code on the remote website changes, the SHA384 function will produce a hash that will not match the second part of the integrity value.

In short, if the code on the remote server has changed, your browser will refuse to run it.