Subresource Integrity (SRI)
May 20, 2023
How SRI Works
SRI works by adding a hash of the resource to the HTML file that references it. When the browser loads the resource, it recalculates the hash and compares it to the hash in the HTML. If they match, the resource is considered valid and is loaded. If they do not match, the browser will not load the resource and will instead display an error message.
To add SRI to a resource, the developer must first generate a hash of the file. This can be done manually using a hashing tool, or automatically using a build tool or a Content Delivery Network (CDN) that supports SRI. The resulting hash is added to the resource’s HTML tag as an attribute, along with the attribute
<link rel="stylesheet" href="mystyles.css" integrity="sha384-LBcLJhBz2QvuXoCfXKatXcHnN1Dj+gGdCY8zoeFGwv+xcFMppC4zXuL3qXh4p4qB" crossorigin="anonymous">
In the above example, the integrity attribute contains the hash of the mystyles.css file. The crossorigin attribute is also included to allow the browser to request the resource from a different domain, if necessary.
Benefits of SRI
The main benefit of SRI is increased security. By verifying the integrity of a resource, developers can ensure that it has not been modified or replaced by a malicious actor. This helps to prevent attacks such as cross-site scripting (XSS) and code injection, which can be used to steal user data or take control of a website.
SRI can also help to improve the reliability of web pages. By ensuring that resources are loaded from a trusted source, developers can avoid common problems such as broken links, slow loading times, and unexpected behavior. This can lead to a better user experience and increased engagement.
Limitations of SRI
While SRI provides an extra layer of security, it is not a foolproof solution. There are several limitations to consider when implementing SRI.
Limited Browser Support
Although SRI is supported by all modern browsers, some older browsers may not support it or may not enforce it correctly. This can lead to compatibility issues and unexpected behavior. Developers should test their web pages on a range of browsers and devices to ensure that SRI is working as intended.
Another limitation of SRI is the possibility of hash collisions. This occurs when two different files have the same hash, which can cause the browser to load an incorrect resource. While the likelihood of a hash collision is low, it is still a possibility that developers should be aware of.
Implementing SRI requires additional steps and maintenance compared to standard resource loading. Developers must generate and update the resource hashes for each resource, as well as ensure that they are using a trusted source for the resources. This can add complexity to the development process and increase the risk of human error.