By default, WordPress allows an unauthenticated user to view the list of the registered users with the help of the REST API. But, for example, to view the list of the users in the Dashboard, the user needs to have `list_users` capability (that is, be an Administrator). While the REST API does not expose sensitive information (such as emails) to unauthenticated users, it may be desirable to restrict `users` endpoint form unauthenticated users.
Fortunately, this is easy.
add_filter('rest_pre_dispatch', function($result, \WP_REST_Server $srv, \WP_REST_Request $request) {
$method = $request->get_method();
$path = $request->get_route();
if (('GET' === $method || 'HEAD' === $method) && preg_match('!^/wp/v2/users(?:$|/)!i', $path)) {
if (!current_user_can('list_users')) {
return new \WP_Error('rest_user_cannot_view', 'Sorry, you are not allowed to use this API.', ['status' => rest_authorization_required_code()]);
}
}
return $result;
}, 10, 3);
The first `if` checks the request method and the endpoint called, the second `if` checks whether the user has necessary capabilities. You may want to customize these checks to suite your needs. By returning `WP_Error`, we effectively stop the further processing of the request, and return this error to the caller.
Enjoy! 🙂
Useful links: