Adding nonce to <script> tag

csp nonce
nonce attribute
csp nonce generator
jquery nonce
csp nonce not working
angular csp nonce
nonce hash csp
nonce in css

I'm wondering how to add nonce to my all <script> tags on page based on WordPress. For example please find some code below:

$my_nonce = wp_create_nonce('nonce-'.rand());
$nonces = "Content-Security-Policy: script-src 'self nonce-".$my_nonce."'";
header( "{$nonces}");

wp_localize_script( 'my_loadmore', 'my_loadmore_params', array(
'ajaxurl' => site_url() . '\/wp-admin\/admin-ajax.php',
'posts' => json_encode( $wp_query->query_vars ), 
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
         'max_page' => $wp_query->max_num_pages,
) );`

And I want to have something like this:

<script nonce="nonce-value">...</script>

Where nonce-value is random.

This only one of places where I need this, is there any idea how to add it globally to <script> tag?

Haven't tested this, but Wordpress does provide a script_loader_tag filter which allows you to modify the generated script tags from enqueued scripts.

add_filter( 'script_loader_tag', 'add_nonce_to_script', 10, 3 );

function add_nonce_to_script( $tag, $handle, $src ) {
    global $my_nonce;
    return '<script type="text/javascript" src="' . esc_url( $src ) . '" nonce="' . esc_attr( $my_nonce ) . '"></script>';
}

What's the purpose of the HTML "nonce" attribute for script and style , Looks like it's just an extra bit of security for your site, you add it to a link or a form and when the page is served, if the nonce doesn't match yours, then you don't� Definition. A nonce is an arbitrary number used only once in a cryptographic communication, in the spirit of a nonce word.They are often random or pseudo-random numbers. Many nonces also include a timestamp to ensure exact timeliness, though this requires clock synchronization between organizations.

Try this code,

add_filter('script_loader_src','add_nonce_to_script',10,2);
function add_nonce_to_script($src, $handle){
   $my_nonce = wp_create_nonce('nonce-'.rand());
   return $src.' nonce= '.$my_nonce;
}

Hope this will helps you. For more example,

Adding Additional Attributes in Script Tag

WordPress Nonces � WordPress Codex, [This thread is closed.] I absolutely love this plugin, but I also love security. I found a plugin that adds nonce's to scripts, but it breaks… This includes the following capabilities: * Generate nonce * Generate hash of nonce * Add nonce to attributes and hash to additional parameters of authentication request * Propagate hash to authentication response * Verify hash upon receipt of response by hashing original nonce * Complete all relevant tests Fixes/implements spring-projectsgh-4442

I setup a function in functions.php to generate a the nonce using the built wordpress function.

add_action( 'run_custom_nonce_value', 'custom_nonce_value' );
function custom_nonce_value () {

    $created_nonce = wp_create_nonce();
    define( 'NONCE_RANDVALUE', $created_nonce ); 

}

Then I setup this filter to add the nonce value to all of the scripts

add_filter( 'script_loader_tag', 'add_nonce_to_script', 10, 3 );
function add_nonce_to_script( $tag, $handle, $source ) {

    custom_nonce_value();
    $val_nonce = NONCE_RANDVALUE;

    $search = "type='text/javascript'";
    $replace = "type='text/javascript' nonce='".$val_nonce."' ";
    $subject = $tag;

    $output = str_replace($search, $replace, $subject);
    return $output;
}

This solution will add the nonce to all correctly registered scripts.

Adding nonce to scripts for Content Security Policy?, This works because even if an attacker manages to inject their own script tag on the page and even add a nonce attribute, they won't know� Nonce: A nonce ("number only used once") is a number added to a hashed block that, when rehashed, meets the difficulty level restrictions. The nonce is the number that blockchain miners are

Locking Down Your Website Scripts with CSP, Hashes, Nonces, Refers to the empty set; that is, no URLs match. The single quotes are required. ' nonce-<base64-value>': An allow-list for specific inline scripts� Don't forget to include nonce checks! } add_action( 'save_post', 'wpdocs_save_meta_box' ); Expand full source code Collapse full source code. Log in to add feedback;

CSP: script-src, The addition of a client nonce ("cnonce") helps to improve the security in some ways as implemented in digest access authentication. To ensure that a nonce is�

Cryptographic nonce, webpack is capable of adding nonce to all scripts that it loads. To activate the feature set a __webpack_nonce__ variable needs to be included in your entry�

Comments
  • What are you trying to accomplish? This isn't the normal way nonces are used in wordpress. There might be an answer to "how do you add a nonce to script tags globally?" But I don't think that's what you really want. Globally in what sense? ALL script tags? Huh?
  • why do you want to add the nonce to script tag? You can set id for it.
  • I assume this is for content security policy purposes.
  • This wouldn't pass the CSP since it's generating a new nonce every single call.
  • you used the rand() function. So, it will always pick a new random number for each in your nonce attribute.