Get user in rest API endpoint

时间:2019-08-06 作者:Azer

I\'m making some API endpoints that require me to confirm who the user is, and what they can do, before I let them use the endpoint.

However, I can\'t seem to get the current user.

My endpoint:

function register_api_hooks() {
  register_rest_route(
    \'bacon\', \'/user/\',
    array(
      \'methods\'  => \'POST\',
      \'callback\' => \'makinbacon\',
    )
  );
}

function makinbacon(WP_REST_Request $request){

    return json_encode(wp_get_current_user());
}

add_action( \'rest_api_init\', \'register_api_hooks\' );

My fetch in the client:

fetch(\'/wp-json/bacon/user\', {
    method: \'POST\',
    headers: {
        \'Content-Type\': \'application/json\',
    },
    credentials: \'same-origin\',
})
.then((response) => {
    return response.json();
})
.then(function(json) {
    console.log(json);
});

The fetch code is included in a normal wordpress page on the same domain and installation of wordpress as the API endpoint. Also, I am logged in as an admin user.

The result:

{"data":{},"ID":0,"caps":[],"cap_key":null,"roles":[],"allcaps":[],"filter":null}

So it seems that the endpoint in itself is working. I\'m not getting any errors, and it does return what seems to be a user. Just that the user is empty.

What else I have tried:

As some answers in similar questions suggested, I have tried including the global $current_user. This gave the same result.

function makinbacon(WP_REST_Request $request){

    global $current_user;

    return json_encode(wp_get_current_user());
}

I have also tried setting credentials to include in the fetch call, as well as trying to change both the fetch call and the endpoint to a GET request.

Everything gives the same empty user.

I also tried to do other things in the endpoint, like creating a post, updating a post, etc. That worked fine.

So far the only thing I haven\'t been able to do in the endpoint is to fetch information about the current user.

Any ideas?

1 个回复
最合适的回答,由SO网友:Azer 整理而成

多亏了雅各布·皮蒂,我才解决了这个问题。

如果希望使用当前用户的信息,则必须在REST API请求中包含WordPress Javascript API中的nonce。

WordPress documentation:

如果未提供nonce,API会将当前用户设置为0,将请求转换为未经验证的请求,即使您登录到WordPress。

换句话说,即使没有nonce,端点也会被超越,但任何获取当前用户信息的尝试都将失败/导致用户对象为空。

相关推荐

使users.php搜索包含特定的用户元数据字段,而不会影响SQL查询本身

我想让管理员通过wordpress/wp admin/users中一个名为“indice de busqueda”的元值来搜索用户。php页面如何以这种方式连接到搜索框中,以便将查询更改为如下所示? $query = get_users([ \'meta_key\' => \'indice de busqueda\', \'meta_value\' => $search_value, \'meta_compare\'=>\