gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:23:41 28 4
gpt4 key购买 nike

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

现在我无法让随机数的东西工作。
这是我到目前为止所做的:

我添加了以下端点:

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

register_rest_route('frontend', '/customer/', array(
'methods' => 'POST',
'callback' => 'create_user_and_login'
));

这些是我的功能:
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;
}

如果我现在运行 POST 到 /customer触发 create_user_and_login() ,新创建的 nonce 在 ajax 响应中返回。然后我使用返回的 nonce 来运行我的下一个请求,一个 GET 到 /customer?_wpnonce=MY-NONCE ,但我得到错误:
{
"code": "rest_cookie_invalid_nonce",
"message": "Cookie nonce is invalid",
"data": {
"status": 403
}
}

我查了 the nonce documentation但我找不到我的问题的解决方案。会不会是 session 不同步?以便在错误的 session 或 wp_set_auth_cookie 上创建随机数和 wp_set_current_user没有正确调用?还是我必须使用 wp_localize_script 功能?这会出现问题,因为我希望将 ReactJS 和 Wordpress 后端分开。

POST 后我得到了两个 cookie,一个 wordpress cookie 和 wordpress_logged_in曲奇饼。

我错过了什么?

最佳答案

Check this answer

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

如答案所示,添加以下钩子(Hook)(例如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' );

关于ajax - Wordpress Auth + Nonce + Ajax + 无模板 - Cookie nonce 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565162/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com