How do you add nonce to script tag?

How do you add nonce to script tag?

There are a few steps involved to allow-list an inline script using the nonce mechanism:

  1. Generating values. From your web server, generate a random base64-encoded string of at least 128 bits of data from a cryptographically secure random number generator.
  2. Allow-listing inline script.
  3. Sending a nonce with a CSP header.

What is script nonce?

So the nonce attribute is way to tell browsers the inline contents of a particular script or style element weren’t injected into the document by some (malicious) third party, but were instead put in the document intentionally by whoever controls the server the document is served from.

What is an inline script?

When a script tag is used in the HTML file, it is called inlining. This means no external JS file is used instead javascript is put into an HTML file. Modern code has moved from manual coding and customized structures to templates that provide a framework for effective code creation processes.

When to use a nonce instead of a hash?

In some situations using a nonce doesn’t make sense, in those cases you can use a CSP hash instead of a nonce. There is one other workaround to this problem called unsafe-inline, but as its name suggests it is not really a good idea to use it (except in specific conditions).

How to generate a nonce for a script?

The nonce should be generated using a cryptographically secure random generator The nonce should have sufficient length, aim for at least 128 bits of entropy (32 hex characters, or about 24 base64 characters). Script tags that have a nonce attribute must not have any untrusted / unescaped variables within them.

How to allow inline scripts in CSP reference?

Assuming our nonce value is r@nd0m (you need to randomly generate a new nonce for every HTTP request), we can now use an inline script tag like this: A second approach to allow inline scripts is to use a hash, with this approach you compute the hash of your JavaScript code, and put the value in our CSP policy:

What should the nonce of a script tag be?

The nonce should be generated using a cryptographically secure random generator; The nonce should have sufficient length, aim for at least 128 bits of entropy (32 hex characters, or about 24 base64 characters). Script tags that have a nonce attribute must not have any untrusted / unescaped variables within them.