Open In App

HTML nonce Attribute

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The HTML nonce attribute is a global content attribute that defines a cryptographic nonce(" number used once "). It is used by Content Security Policy(it is an additional layer of security that helps to detect and mitigate certain types of attacks like data injection attacks) to check whether a given fetch will be allowed to proceed for a given element or not. Generally, the attribute nonce specifies the way by which the browser is told that inline contents of some style element or specific/particular script were not injected into the document by third parties and were put in the document intentionally by whoever controls the server from where the document is served.

It allows the list of specific elements such as some specific inline script or style elements. It helps to avoid the use of the CSP unsafe-inline directive that would allow-list all inline styles.

Usage of nonce attribute 

For using none, provide the script tag a nonce attribute. The value of the nonce attribute must match one in the list of trusted sources. 

Example: In this example we showcases the nonce attribute, enhancing security by allowing only styles and scripts with matching nonce values to execute.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Nonce Attribute Example</title>
    <style nonce="EDNnf03nceIOfn39fn3e9h3sdfa">
        /* This style block is allowed because it has the correct nonce */
        body {
            background-color: #f0f0f0;
        }
    </style>
</head>

<body>
    <h1>Welcome to My Website</h1>
    <script nonce="EDNnf03nceIOfn39fn3e9h3sdfa">
        // This script is allowed because it has the correct nonce
        console.log('Hello, world!');
    </script>
</body>

</html>

Now this nonce needs to be added to our script-src directive appended to the nonce- keyword.

Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'

Supported Browsers:


Next Article

Similar Reads