[英]How to implement Content Security Policy with WordPress Nonces in PHP using PHP header-method?
Currently I am trying to implement a Content Security Policy on a WordPress Landing page.目前我正在尝试在 WordPress 登陆页面上实施内容安全策略。 I am using the following header-method in PHP to implement a Content Security Policy:我在 PHP 中使用以下标头方法来实现内容安全策略:
header("Content-Security-Policy:default-src 'none'; script-src 'nonce-RandomSeq' 'nonce-hzthedtrh5' 'nonce-hjjftzrf56zf' ... ")
And I am attempting to use WordPress Nonce to create random nonces for a inline Javascript code我正在尝试使用WordPress Nonce为内联 Javascript 代码创建随机 nonce
<?php
$nonce = wp_create_nonce( 'my-nonce' ); ?>
<script type="text/javascript" nonce="<?php echo $nonce; ?>">
// some javascript code
</script>
This example works when I specifiy the nonce with a string like "435234JHHJK2", but when I try to put a variable in the header like this:当我使用“435234JHHJK2”之类的字符串指定随机数时,此示例有效,但是当我尝试将变量放入标头时,如下所示:
header("Content-Security-Policy:default-src 'none'; script-src 'nonce-".$nonce."' 'nonce-hzthedtrh5' 'nonce-hjjftzrf56zf' ... ")
The random nonce, created by wp-nonce is not recognized and the given script won't be executed.无法识别由 wp-nonce 创建的随机 nonce,并且不会执行给定的脚本。
So what am I doing wrong?那么我做错了什么?
Found the solution:找到了解决办法:
PHP does not accept variables in single quotes liike in 'noce-".$nonce."'
Solution is to save the whole in CSP information in an external string variable: PHP 不接受单引号中'noce-".$nonce."'
变量,例如'noce-".$nonce."'
解决方案是将整个 CSP 信息保存在外部字符串变量中:
$csp = "Content-Security-Policy: script-src 'nonce-".$nonce1."' 'nonce-".$nonce2."'...";
and to include this variable into the PHP header method:并将此变量包含到 PHP 标头方法中:
header( "{$csp}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.