Securing JavaScript Applications with Subresource Integrity (SRI): A Comprehensive Guide
Tags: javascript, websecurity, sri, webdev
Published: 2024-07-06 08:25:48

---
title: Securing JavaScript Applications with Subresource Integrity (SRI): A Comprehensive Guide
published: true
description: 
tags: JavaScript, WebSecurity, SRI, WebDevelopment 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vwi8htqqlkhaf69d2x4l.jpg
# Use a ratio of 100:42 for best results.
#published_at: 2024-07-06 07:57 +0000
---
## Introduction 
In today's web development landscape, ensuring the security of your applications is paramount. One effective method to enhance security is by using Subresource Integrity (SRI). This feature allows browsers to verify that resources they fetch (like scripts or styles) are delivered without unexpected manipulation. In this blog post, we will explore what SRI is, how it works, and how you can implement it in your JavaScript applications with real-world examples. We will also demonstrate a potential security attack without SRI and how SRI can prevent such attacks.

## What is Subresource Integrity (SRI)?
Subresource Integrity (SRI) is a security feature that enables web browsers to verify that files they fetch (for example, from a CDN) are delivered without any alterations. It does this by comparing the fetched file's hash with a hash specified in the HTML file. If the hashes don't match, the browser will block the file from loading, protecting your application from malicious modifications.

## Why Use SRI?
Using SRI offers several benefits:

**Security:** Protects against malicious content injected into third-party resources.

**Integrity:** Ensures the fetched resources are exactly what the developer intended.

**Trust:** Builds user trust by safeguarding the application from external threats.

## Example of a Security Attack Without SRI
Let's consider a scenario where you include a JavaScript library from a third-party CDN without using SRI. An attacker could potentially compromise the CDN and inject malicious code into the library.

### HTML Without SRI:
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vulnerable Example</title>
</head>
<body>
    <h1>Vulnerable jQuery Example</h1>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            console.log('jQuery loaded');
        });
    </script>
</body>
</html>
```
## Potential Attack:
An attacker compromises the CDN and injects malicious code:
```js
(function() {
    console.log('Malicious code executed');
    // Malicious actions such as stealing cookies or redirecting users
    document.location = 'http://malicious-site.com';
})();

```
When users load your site, the compromised jQuery file executes the malicious code, leading to security breaches.

## How SRI Prevents the Attack
By implementing SRI, you can ensure that only the intended version of the resource is loaded, blocking any altered versions.

### 1. Generate the Hash:
You need to generate the hash of the resource you want to include. You can use tools like OpenSSL or online hash generators. For example, to generate a hash for a JavaScript file using OpenSSL, you can use the following command:
```js
openssl dgst -sha384 -binary your-file.js | openssl base64 -A
```

### 2. Add the Integrity Attribute:
Once you have the hash, you add it to the script tag using the integrity attribute. You also need to add the crossorigin attribute to handle cross-origin requests.
```js
<script src="https://example.com/your-file.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GH1p3lDVS8vksP1BxlYP4yYPHNBEU1WZwCkJ0" crossorigin="anonymous"></script>

```
### 3. HTML with SRI:
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure Example</title>
</head>
<body>
    <h1>Securing JavaScript with SRI</h1>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha384-KyZXEAg3QhqLMpG8r+Knujsl5/0p6b4T1/VoVwlSIIecL50R5yI4zj6P0r4fApd8"
            crossorigin="anonymous"></script>
    <script>
        $(document).ready(function(){
            $('body').append('<p>jQuery is loaded securely with SRI!</p>');
        });
    </script>
</body>
</html>
```
## Detailed Steps to Prevent Attacks Using SRI

### 1. Identify the Resource:
Determine which external resources (scripts, styles) you need to secure. In this example, we'll secure jQuery.

### 2. Generate the SRI Hash:
Use an SRI hash generator. For instance, the SRI Hash Generator website can create hashes for you.

### 3. Update Your HTML:
Add the integrity attribute to your script or link tags along with the crossorigin attribute. Here's the example with jQuery:
```js
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha384-KyZXEAg3QhqLMpG8r+Knujsl5/0p6b4T1/VoVwlSIIecL50R5yI4zj6P0r4fApd8"
        crossorigin="anonymous"></script>

```
### 4. Verify the Setup:
Load your webpage and check the browser's console for any SRI-related errors. If the hash doesn't match, you'll see an error, and the resource won't load.

## Real-World Example
Let's walk through a real-world example of securing a JavaScript library from a CDN with SRI.

### 1. Include jQuery with SRI:
Suppose you want to include jQuery from a CDN in your project. First, you need to generate the SRI hash for the jQuery file. You can find pre-generated hashes for popular libraries on sites like SRI Hash Generator.

### 2. Add jQuery to Your HTML:
Use the provided hash and add it to your HTML file.
```html 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure jQuery Example</title>
</head>
<body>
    <h1>Securing JavaScript with SRI</h1>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha384-KyZXEAg3QhqLMpG8r+Knujsl5/0p6b4T1/VoVwlSIIecL50R5yI4zj6P0r4fApd8"
            crossorigin="anonymous"></script>
    <script>
        $(document).ready(function(){
            $('body').append('<p>jQuery is loaded securely with SRI!</p>');
        });
    </script>
</body>
</html>
```
In this example, we included jQuery from a CDN and used the SRI hash to ensure its integrity. If the file is altered in any way, the browser will block it from loading.

### Best Practices for Using SRI

**Always use HTTPS:** SRI only works over HTTPS.

**Regularly update hashes:** When you update your resources, remember to generate new hashes.

**Use trusted CDNs:** Ensure the CDNs you use are reputable and secure.

## Conclusion
Subresource Integrity (SRI) is a powerful tool to help secure your JavaScript applications by ensuring that the resources you load have not been tampered with. By implementing SRI, you can protect your users from malicious content and improve the overall security of your web applications. Start using SRI today to enhance the security and integrity of your projects.