简体   繁体   English

WordPress nonces 错误并且不起作用?

[英]WordPress nonces are wrong and not working?

I really don't understand what is happening with WordPress nonces, i think they're wrong, or they're useless.我真的不明白 WordPress nonces 发生了什么,我认为它们是错误的,或者它们没用。

I always have troubles working with that nonces, WordPess never been able to check one nonce successfully, i will put here 2 cases in which the nonces aren't working, in all cases i tried to maken aj AJAX request:我总是在处理这些 nonce 时遇到麻烦,WordPess 永远无法成功检查一个 nonce,我将在这里放置 2 个 nonce 不起作用的情况,在所有情况下,我都尝试发出 aj AJAX 请求:

CASE 1:情况1:

In this case i tried to use wp_rest nonce to verify it:在这种情况下,我尝试使用 wp_rest nonce 来验证它:

PHP (plugin.php): 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: 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: () => { ... }
});

It only works when the user is logged in, but i'm not using users on my website, the only user is admin, so, it doesn't work for guests users (And i need to works for them), when is a guest user, it returns: rest_cookie_invalid_nonce 403 error PD.它仅在用户登录时有效,但我没有在我的网站上使用用户,唯一的用户是管理员,因此,它不适用于来宾用户(我需要为他们工作),什么时候是来宾用户,它返回: rest_cookie_invalid_nonce 403 error PD。 I don't put the code of the ajax functions 'cause it doesn't even get to run them我没有放置 ajax 函数的代码,因为它甚至无法运行它们

CASE 2案例二

So i don't want to put more code here, but, for this case, in wp_create_nonce function i change the wp_rest string for any_value string所以我不想在这里放更多代码,但是,对于这种情况,在wp_create_nonce函数中,我将wp_rest字符串更改为any_value字符串

In the $.ajax call y delete the headers option, and y pass the nonce in the data option as "nonce_field", and in my rest functions i do this:在 $.ajax 调用中删除headers选项,并将data选项中的随机数作为“nonce_field”传递,在我的其余函数中,我这样做:

var_dump(check_ajax_referer("any_value", "nonce_field"));

And it always returns false, the nonce never pass, and also happens with:它总是返回 false,nonce 永远不会通过,并且也会发生:

var_dump(wp_verify_nonce($_POST["nonce_field"], "any_value"));

So the nonce never is true, and i don't know why, it should be an WordPress issue, i'm using WordPress 5.5 (The most recent version) so i think if it's always return false then the nonce in WordPress are useless所以随机数永远不会是真的,我不知道为什么,它应该是一个 WordPress 问题,我使用的是 WordPress 5.5(最新版本)所以我认为如果它总是返回 false 那么 WordPress 中的随机数是无用的

Or can you help me what i'm doing wrong?或者你能帮我做错什么吗? Thanks a lot!!!非常感谢!!!

When you take a look at the wp_verify_nonce function in wp-includes/pluggable.php, you'll see that it is a user based validation.当您查看 wp-includes/pluggable.php 中的wp_verify_nonce函数时,您会发现它是基于用户的验证。 But in your case you want to make it public and in this case there is no need for nonces.但是在您的情况下,您希望将其公开,在这种情况下,不需要随机数。 Just tell WordPress the route is to be public by adding 'permission_callback' => '__return_true' into the args array when creating your custom route via the register_rest_route function:在通过register_rest_route函数创建自定义路由时,只需将'permission_callback' => '__return_true'到 args 数组中,告诉 WordPress 路由是公开的:

    public function __construct() {
        add_action( 'rest_api_init', array( $this, 'registerRoutes' ), 10 );
    }

    public function registerRoutes() {
        register_rest_route(
            'mybase',
            'my/custom/path',
            array(
                'methods'             => 'POST',
                'callback'            => array( $this, 'addToCart' ),
                'permission_callback' => '__return_true',
                'args'                => array(
                    'product_id'   => array(
                        'type'              => 'integer',
                        'sanitize_callback' => 'absint',
                    ),
                    'variation_id' => array(
                        'type'              => 'integer',
                        'sanitize_callback' => 'absint',
                    ),
                    'quantity'     => array(
                        'type'              => 'integer',
                        'sanitize_callback' => 'absint',
                    )
                ),
            )
        );

    }

Then just remove the x-wp-nonce header from the ajax function:然后只需从 ajax 函数中删除 x-wp-nonce 标头:

$.ajax({
   url: script_data.endpoint_url,
   data: [], // Here is some real data
   type: "post",
   dataType: "json",
   success: () => { ... },
   error: () => { ... }
});

WordPress checks the nonce automatically (by running the wp_verify_nonce function against the "wp_rest" action name) when you add an X-WP-Nonce header to your ajax request or a "_wpnonce" key to your POST/GET arguments/parameters.当您向 ajax 请求添加X-WP-Nonce标头或向 POST/GET 参数/参数添加“_wpnonce”键时,WordPress 会自动检查随机数(通过针对“wp_rest”操作名称运行wp_verify_nonce函数)。

Use wp_verify_nonce( $_POST["nonce_field"], "wp_rest" );使用 wp_verify_nonce( $_POST["nonce_field"], "wp_rest" ); for verify nonce.用于验证 nonce。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM