Wordpress Auth + Nonce + Ajax + 无模板 - Cookie nonce 无效

Dar*_*rio 7 authentication ajax rest wordpress nonce

我了解创建自己的模板时使用随机数的过程。但是我正在开发一个 ReactJS 应用程序,它只使用 Wordpress REST API 来提取数据,所以用户永远不会访问 index.php,而是对 WP Rest Api 进行 Ajax 调用。

现在我无法让 nonce 工作。这是我到目前为止所做的:

我添加了以下端点:

register_rest_route('frontend', '/customer/', array(
    'methods' => 'GET',
    'callback' => 'get_customer'
));

register_rest_route('frontend', '/customer/', array(
    'methods' => 'POST',
    'callback' => 'create_user_and_login'
));
Run Code Online (Sandbox Code Playgroud)

这些是我的功能:

function get_customer()
{
    return get_current_user_id();
}


function create_user_and_login(){
    // dummy data for testing
    $credentials = ['user_login' => 'mail@mymail.de', 'user_password' => 'XXXX', 'remember' => true];

    // create a new user/customer via woocommerce
    $customerId = wc_create_new_customer($credentials['user_login'], $credentials['user_login'], $credentials['user_password']);
    if(is_a($customerId,'WP_Error')) {
        return $customerId;
    }
    // get the user & log in
    $user = get_user_by( 'id', $customerId );
    if( $user ) {
        wp_set_current_user( $customerId);
        wp_set_auth_cookie( $customerId );
    }
    // create new nonce and return it
    $my_nonce = wp_create_nonce('wp_rest');
    return $my_nonce;
}
Run Code Online (Sandbox Code Playgroud)

如果我现在运行 POST 到/customertriggers create_user_and_login(),则在 ajax 响应中返回新创建的随机数。然后我使用返回的随机数来运行我的下一个请求,一个 GET to /customer?_wpnonce=MY-NONCE,但我收到错误:

{
    "code": "rest_cookie_invalid_nonce",
    "message": "Cookie nonce is invalid",
    "data": {
        "status": 403
    }
}
Run Code Online (Sandbox Code Playgroud)

我检查了 nonce 文档,但找不到解决我的问题的方法。会不会是会话不同步?因此,该随机数是在错误的会话,或者创建wp_set_auth_cookiewp_set_current_user不正确叫什么名字?还是我必须使用该wp_localize_script功能?这会出现问题,因为我希望将 ReactJS 和 Wordpress 后端分开。

POST 后我得到了两个 cookie,一个wordpresscookie 和一个wordpress_logged_incookie。

我错过了什么?

Fel*_*iel 8

检查这个答案

似乎当您调用$my_nonce = wp_create_nonce('wp_rest');nonce 时,是使用旧会话 cookie 创建的,即使您调用wp_set_auth_cookiewp_set_current_user。但是在下一个请求中会话被更新,这意味着随机数是错误的。

在答案中,添加以下钩子(例如functions.php)以强制更新cookie:

        function my_update_cookie( $logged_in_cookie ){
            $_COOKIE[LOGGED_IN_COOKIE] = $logged_in_cookie;
        }
        add_action( 'set_logged_in_cookie', 'my_update_cookie' );
Run Code Online (Sandbox Code Playgroud)