How to add a nonce to an inline script in WordPress

csp nonce
content security policy: ignoring 'unsafe-inline''' within script-src: 'strict-dynamic' specified
csp hash generator

I'm trying to add a nonce to the inline scripts inserted in WordPress by wp_add_inline_script and wp_localize_script, but I can't figure out how to do it. It looks there are no WordPress filters for that. My goal is to have a nonce for inline scripts, so I can define a Content Security Policy that would not break common plugins that insert inline scripts. At the end the result should be something that looks like:

<script type="text/javascript" nonce="xxxxxxxxxx">....</script>

where xxxxxxxx is the nonce.

Do you have any ideas?

Try to use wp_enqueue_scripts hook

function my_special_inline_script() {
    ?>
    <script>
        // your JS code
    </script>
    <?php
}

add_action( 'wp_enqueue_scripts', 'my_special_inline_script', 1, 1 );

or

function theme_prefix_enqueue_script() {
   wp_add_inline_script( 'jquery', 'jQuery(document).ready(function(){});' );
}
add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );

Support for script nonces?, Hi Is there any intention to enable the ability to insert nonce values in CSP so that it doesn't nonce for script-src which would allow me to disable unsafe-inline. Example In this simple example, we create an nonce and use it as one of the GET query parameters in a URL for a link. When the user clicks the link they are directed to a page where a certain action will be performed (for example, a post might be deleted).

As the HTML for inline scripts are generated by the WordPress code

sprintf( "<script type='text/javascript'>\n%s\n</script>\n", ... )

you cannot add an attribute to the HTML script element using wp_add_inline_script() as <script type='text/javascript'> is hard coded.

However, the filter 'script_loader_tag' will allow you to change the HTML for script elements just before it is outputted by WordPress.

Note that the filter 'script_loader_tag' will not be applied to script elements added by calling wp_localize_script() since these are outputted by the WordPress code:

echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
echo "</script>\n";

Since these are echoed and <script type='text/javascript'> is hard coded you cannot add an attribute to the HTML script elements of wp_localize_script().

Generating an nonce for Content Security Policy and all scripts , WP's nonces aren't true nonces as they are valid for about 24 hours. As for generating the nonce, you don't want to use a WordPress based nonce, Generate the number in the body of your plugin code, put it in a global  nonce-support has in the past already been requested, but it isn’t in AO yet.. How does WP-CSP break AO, is it that the AO’d scripts aren’t found, so don’t get a nonce and hence are not loaded?

Bit late to the party but I just faced this exact problem for the same reasons.

I solved it for wp_add_inline_script by a bit of simple str_replace action.

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

function add_nonce_to_script_tag( $tag, $handle, $src ) {

  // Check the $handle and respond accordingly
  if ( $handle === 'my-script' ) {
    $nonce_value = wp_create_nonce('my__script__nonce'); // or ref to an existing nonce
    $replace = sprintf("javascript' nonce='%s'>", $nonce_value );
    $tag = str_replace( "javascript'>", $replace, $tag);
  }

  return $tag;
}

// Then... $data is the inline JS from wherever
wp_add_inline_script('my-script', $data, 'before');

Once the inline script loads, I am seeing the script tag output with a nonce attribute. This is working fine with my Content-Security-Policy.

WordPress/two-factor, Without running script-src: unsafe-inline this means it is impossible to provide a and the inclusion of https://core.trac.wordpress.org/ticket/39941 script nonce's has The plugin uses core wp_localize_script() to include some of the dynamic​  Content-Security-Policy: script-src 'nonce-123abc' And then whenever you use inline JavaScript, you add a nonce attribute to the script element: <script nonce="123abc"> doSomething() </script> And when the browser encounters a script tag with the wrong nonce (or no nonce), it refuses to execute that JavaScript.

Better Way to Add Inline Scripts, If you are a WordPress developer, you may have used the WordPress hook wp_print_scripts to add any necessary inline JavaScript. Alternately  In this example the basic nonce process: Generates a nonce with the wp_nonce_field() function. The nonce is submitted with the form submission. The nonce is verified for validity using the wp_verify_nonce() function.

Locking Down Your Website Scripts with CSP, Hashes, Nonces, By Default, Inline Scripts Are Out manages to inject their own script tag on the page and even add a nonce attribute, they won't know what the  Add a notice with a link to the guide when editing the privacy policy page. Enqueue assets needed by the code editor for the given settings. Add hooks for enqueueing assets when registering all widget instances of this widget class. Loads the required media files for the media manager and scripts for media widgets.

WordPress/Woocommerce Inline Javascript adding Nonce and CSP , I have been trying to add a Nonce to inline JS in Wordpress primarily focusing on WooCommerce. So far, I've managed to add the Nonce to registered JS but the  add_filter( 'nonce_life', function { return 4 * HOUR_IN_SECONDS; } ); Note that just as a WordPress nonce is not "a number used once", nonce lifetime isn't really nonce lifetime. WordPress uses a system with two ticks (half of the lifetime) and validates nonces from the current tick and the last tick.

Comments
  • check this link w3.org/TR/CSP3/#strict-dynamic-usage and this core.trac.wordpress.org/ticket/39941 ... I don't have any idea , I 'm also looking for this.
  • thank you for your comment. If you look at the second link you have provided, on the bottom you will see my question :) Reading the first link, we could think to use hashes instead of nonces, but I also don't figure out how to create an hash for each inline script, I don't see any hook to do that.
  • gist.github.com/shadyvb/574ead376eda7617e0f5e2a061815665 check this link if this helpful
  • thank you very much for your comment. I had already tried with the filter script_loader_tag but without success. On my opinion the possibility to add a nonce to inline scripts should be provided by the WordPress core. As it is now it looks impossible to implement a serious Content Security Policy without break third parties plugins that haven't taken it in account. For building a single site it's easier. My goal was to make a theme that could support the CSP, but if the user decides to activate it, all the inline scripts of the common plugins as WooCommerce will be deactivated. I will renounce
  • The filter for ''script_loader_tag' should work for everything but the scripts added by wp_localize_script(). When WordPress does not have an action/filter to do what you need you can always modify the WordPress core - not best practice but absolutely necessary. Regarding WordPress and CSP I remember thinking about it several years ago and coming to the conclusion it would be very hard to do.
  • Incidentally, modifying the WordPress core can be done in minimally intrusive manner. In this case I would remove the 'wp_head' action 'wp_print_head_scripts' and replace it with my own action. My action would use my own class extension of the core class WP_Scripts. There is only one method WP_Scripts::print_extra_script() you need to modify and that modification is trivial.
  • The main point of modifying the WordPress core in the way I have described is that when a site updates WordPress that site should still run correctly.