快速上下文:我正在评估为我们的 WIP 无外设 WordPress 站点的一些自定义 restful 端点进行身份验证的可能解决方案。
我想要实现的是is_user_logged_in使用基于 cookie 的身份验证在我的自定义端点中返回 true。
这是我当前的设置,这是我尝试过的。
我有以下内容functions.php
// create an endpoint for getting a nonce
function get_nonce() {
return new WP_REST_Response(array('nonce' => wp_create_nonce( 'wp_rest' )));
}
add_action( 'rest_api_init', function () {
register_rest_route('my-site', 'nonce', array(
'methods' => 'GET',
'callback' => __NAMESPACE__ . '\get_nonce'
));
} );
function get_orders() {
if ( !is_user_logged_in() ) {
return new WP_Error( 'not_authorized', 'You are not logged in', array('status' => 401) );
}
$orders = // ...
return new WP_REST_Response($orders);
}
add_action( 'rest_api_init', function () {
register_rest_route( 'my-site', 'orders', array(
'methods' => 'GET',
'callback' => __NAMESPACE__ . '\get_orders',
));
} );
因此,总而言之,这会创建两个端点:
/wp-json/my-site/nonce
生成随机数
/wp-json/my-site/orders
提取一些用户数据
我所做的是:
打电话GET /wp-json/my-site/nonce
来抢随机数
称呼GET /wp-json/my-site/orders?_wpnonce=thepreviousnonce
我得到的是这个错误:
{
"code": "rest_cookie_invalid_nonce",
"message": "Cookie nonce is invalid",
"data": {
"status": 403
}
}
我只是使用浏览器和 URL 来发出请求,并且我已经检查过每个请求中是否包含 cookie。
我错过了什么?为什么我得到 403?
拉莫斯之舞