I want to only permit the execution of specific admin tasks for users who are
- currently logged in to the wp admin panel (via is_user_logged_in) and who
- have a specific capability (via current_user_can).
To do this check; I do:
register_rest_route(
'plugin/v1',
'/resource',
[
[
'methods' => 'GET',
'permission_callback' => function ( WP_REST_Request $request ) {
if(! is_user_logged_in()) { return false;}
if(! current_user_can('edit_pages')) { return false;}
if(wp_verify_nonce($request->get_header('X-WP-Nonce'),'wp_rest') === false ) { return false; }
},
'callback' => 'controller',
'args' => $args
]
]
);
is_user_logged_in()
is passed, but current_user_can
fails, even if I try it with some really basic capability like edit_pages
, and run the request as an Administrator
user.
Interestingly, if I echo json_encode(wp_get_current_user())
in that permission callback, I can see that the caps
property, supposed to represent the user's capabilities, is an empty array. So the admin user has no assigned capabilities, although he's an admin user. Anyone may know why this happens? Because, according to the docs:
Every user logged into WordPress is automatically assigned specific User capabilities depending on their User role.
This does not seem to be the case here??
WP_User::$caps
is layered on top of any capabilities granted by the user's role - it's not unusual for it to be empty.permission_callback
. As stated in my question, I'm usingis_user_logged_in
, hence for authentication, and thencurrent_user_can
for authorization. At the moment, it looks like the user is not set because I did not correctly send the nonce, leading to wp nulling the admin user. On the point of figuring it out; will post my answer below.