1

Hooking into the script_loader_tag hook and generating random strings is no problem, but how can I generate them once per page load and use them in both wp_head and script_loader_tag?

I'd really like to upgrade my CSP, but all the plugins I've found to do it mangle minification.

2
  • edit your question to show the code you tried.
    – mmm
    Jul 20 '18 at 4:59
  • I can't come up with any reasonably clean code that could possibly work, so I've tried no code.
    – Slbox
    Jul 20 '18 at 15:59
0

WP's nonces aren't true nonces as they are valid for about 24 hours. So, if you use the same string in wp_create_nonce( $action ) then WP will always generate the same nonce for a 24 hour period.

0

Actually, you would not use the wp_head action. That happens in the head part of the HTML output. To send a Content-Security-Policy header, or modify an existing one, you would want to hook into the wp_headers filter instead.

As for generating the nonce, you don't want to use a WordPress based nonce, as those are not unique per page load. You will want each load to have a random number generated.

As for using the same number in the wp_headers and the script_loader_tag, well, you just, you know, use the same number in both places. Generate the number in the body of your plugin code, put it in a global variable, then reference that variable from both functions hooked to those filters.

2
  • Are you able to suggest what we can use to generate nonces in Wordpress for use in a CSP please?
    – zigojacko
    Dec 8 '20 at 17:24
  • 1
    @zigojacko Well, php's random_int or random_bytes would be the obvious place to start from.
    – Otto
    Dec 9 '20 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.