Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding nonce to <script> tag

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?

like image 619
Ryszard Bosiak Avatar asked Sep 17 '25 19:09

Ryszard Bosiak


2 Answers

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>';
}
like image 102
Devon Avatar answered Sep 20 '25 09:09

Devon


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.

like image 45
Robbiegod Avatar answered Sep 20 '25 09:09

Robbiegod