我尝试添加自定义请求。
add_action('rest_api_init', function () {
register_rest_route( 'custom', '/login', array(
'methods' => 'GET',
'callback' => function(WP_REST_Request $request) {
return wp_get_current_user();
}
));
});
但它总是返回 ID = 0 的用户; 我也试过这个:
add_action('rest_api_init', function () {
register_rest_route( 'custom', '/login', array(
'methods' => 'GET',
'callback' => function(WP_REST_Request $request) {
return is_user_logged_in();
}
));
});
它总是返回 false。 但用户肯定已登录。
我添加了我的自定义登录
add_action('rest_api_init', function () {
register_rest_route( 'custom', '/login', array(
'methods' => 'POST',
'callback' => function(WP_REST_Request $request) {
$nonce = wp_create_nonce("wp_rest");
$user = wp_signon(array('user_login' => $_POST['username'],
'user_password' => $_POST['password'], "rememberme" => true), false);
if (is_wp_error($user)) {
return $user;
}
//do_action( 'wp_login', "capad" );
//$user['isloggedin'] = is_user_logged_in();
return array('user' => $user,
'nonce' => $nonce);
}
));
});
然后我添加“X-WP-Nonce”作为 http 请求的 header
现在每个请求输出:{"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}
最佳答案
来自Authentication REST API 手册中的章节:
Cookie authentication is the basic authentication method included with WordPress. When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user.
However, the REST API includes a technique called nonces to avoid CSRF issues. This prevents other sites from forcing you to perform actions without explicitly intending to do so. This requires slightly special handling for the API.
For developers using the built-in Javascript API, this is handled automatically for you. This is the recommended way to use the API for plugins and themes. Custom data models can extend wp.api.models.Base to ensure this is sent correctly for any custom requests.
For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to
wp_rest
. These can then be passed to the API via the_wpnonce
data parameter (either POST data or in the query for GET requests), or via theX-WP-Nonce
header.
这是一个 GET 示例:
https://example.tld/wp-json/wp/v2/users/me?_wpnonce=9467a0bf9c
或者在你的情况下:
https://example.tld/wp-json/custom/login/?_wpnonce=9463a0bf9c
从哪里创建随机数
wp_create_nonce( 'wp_rest' );
因此,您很可能在测试自定义端点时忘记了nonce 部分。
希望对您有所帮助!
关于php - 如何使用 Wordpress Rest Api 获取当前登录用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42381521/