【发布时间】:2021-01-02 09:45:14
【问题描述】:
我真的不明白 WordPress nonces 发生了什么,我认为它们是错误的,或者它们没用。
我总是在处理这些 nonce 时遇到麻烦,WordPess 从来没有成功检查过一个 nonce,我将在这里放 2 个 nonce 不起作用的情况,在所有情况下我都试图提出 aj AJAX 请求:
案例 1:
在这种情况下,我尝试使用 wp_rest nonce 来验证它:
PHP (plugin.php):
<?php
require("ajax_endpoints.php");
class MyPluginClass {
public static function setup_plugin() {
add_shortcode("my_shortcode", array(self::class, "my_shortcode_func"));
}
public my_shortcode_func() {
// Only add scripts when this shotcode is used
self::add_plugin_scripts();
wp_enqueue_script("my_script", plugin_url("js/myscript.js", __FILE__), [], "1.0");
wp_localize_script("my_script", "script_data", array(
"endpoint_url" => rest_url("/my/rest"),
"endpoint_url2" => rest_url("/my/rest2"),
"nonce" => wp_create_nonce("wp_rest")
));
}
}
MyPluginClass::setup_plugin();
?>
JS:
$.ajax({
url: script_data.endpoint_url,
data: [], // Here is some real data
type: "post",
dataType: "json",
headers: {
'X-WP-Nonce': script_data.nonce
},
success: () => { ... },
error: () => { ... }
});
它仅在用户登录时有效,但我没有在我的网站上使用用户,唯一的用户是管理员,因此,它不适用于访客用户(我需要为他们工作),当是访客用户时,它返回:rest_cookie_invalid_nonce 403 errorPD。我没有放 ajax 函数的代码,因为它甚至无法运行它们
案例 2
所以我不想在这里放更多代码,但是对于这种情况,在wp_create_nonce 函数中,我将wp_rest 字符串更改为any_valuestring
在 $.ajax 调用中删除headers 选项,然后将data 选项中的随机数作为“nonce_field”传递,在我的其余函数中我这样做:
var_dump(check_ajax_referer("any_value", "nonce_field"));
它总是返回 false,nonce 永远不会通过,并且也会发生:
var_dump(wp_verify_nonce($_POST["nonce_field"], "any_value"));
所以 nonce 永远不会是真的,我不知道为什么,这应该是 WordPress 的问题,我使用的是 WordPress 5.5(最新版本)所以我认为如果它总是返回 false,那么 WordPress 中的 nonce没用的
或者你能帮我解决我做错了什么吗?非常感谢!!!
【问题讨论】: