HTML

Implementing Subresource Integrity (SRI) for External Scripts and Stylesheets

Enhance web security by using Subresource Integrity (SRI) to verify that external scripts and stylesheets hosted on CDNs haven't been tampered with.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SRI Example</title>

    <!-- SECURE: Subresource Integrity for a CSS file from a CDN -->
    <!-- The 'integrity' attribute contains a cryptographic hash of the expected resource content. -->
    <!-- The 'crossorigin' attribute is required for SRI checks. -->
    <link rel="stylesheet"
              href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"
              integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg=="
              crossorigin="anonymous" referrerpolicy="no-referrer" />

    <!-- SECURE: Subresource Integrity for a JavaScript file from a CDN -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
                integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
                crossorigin="anonymous"></script>

    <!-- INSECURE (Without SRI): If this CDN is compromised, malicious code could be injected -->
    <script src="https://example.com/some-library.js"></script>

    <!-- INSECURE (Without crossorigin): SRI check would fail or be skipped -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
                integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="></script>
</head>
<body>
    <h1>Welcome to the SRI Demo</h1>
    <i class="fas fa-check"></i> This icon is from Font Awesome.

    <script>
        // Example of using jQuery from the SRI-protected script
        $(document).ready(function() {
            console.log("jQuery is ready!");
            $('body').append('<p>Content added by jQuery (SRI protected).</p>');
        });
    </script>
</body>
</html>
How it works: Subresource Integrity (SRI) is a security feature that allows browsers to verify that resources (like scripts and stylesheets) fetched from CDNs or other third-party servers have not been tampered with. By including an `integrity` attribute with a cryptographic hash of the expected resource and a `crossorigin` attribute, the browser will block the resource from loading if its actual content does not match the provided hash, protecting against supply-chain attacks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs