admin管理员组

文章数量:1122832

When I use a REST route whilst logged in, and call wp_get_current_user(), no user is found. However, the request method, eg POST is processed without issue. Example REST route registration.

register_rest_route(
    'dewd-test-namespace', //namespace
    'dewd-test-namespace-test-route', //route
    [
     'methods'=>'POST',
     'callback'=>[
          $this,   //object of this class
          'testingUser' //function
      ] 
    ] //params
);

Call to wp_get_current_user() returns this user object:

WP_User Object
(
    [data] => stdClass Object
        (
        )

    [ID] => 0
    [caps] => Array
        (
        )

    [cap_key] => 
    [roles] => Array
        (
        )

    [allcaps] => Array
        (
        )

    [filter] => 
    [site_id:WP_User:private] => 0
)

i.e no user. If a permission callback is added e.g. `

'permission_callback' => function () {

     return current_user_can( 'edit_others_posts' );
 }

A 401 status is returned with the message "Sorry, you are not allowed to do that".

I would appreciate it if anyone knows what I might need to do in order for wp_get_current_user() to return the current user in a REST call.

When I use a REST route whilst logged in, and call wp_get_current_user(), no user is found. However, the request method, eg POST is processed without issue. Example REST route registration.

register_rest_route(
    'dewd-test-namespace', //namespace
    'dewd-test-namespace-test-route', //route
    [
     'methods'=>'POST',
     'callback'=>[
          $this,   //object of this class
          'testingUser' //function
      ] 
    ] //params
);

Call to wp_get_current_user() returns this user object:

WP_User Object
(
    [data] => stdClass Object
        (
        )

    [ID] => 0
    [caps] => Array
        (
        )

    [cap_key] => 
    [roles] => Array
        (
        )

    [allcaps] => Array
        (
        )

    [filter] => 
    [site_id:WP_User:private] => 0
)

i.e no user. If a permission callback is added e.g. `

'permission_callback' => function () {

     return current_user_can( 'edit_others_posts' );
 }

A 401 status is returned with the message "Sorry, you are not allowed to do that".

I would appreciate it if anyone knows what I might need to do in order for wp_get_current_user() to return the current user in a REST call.

Share Improve this question asked Sep 19, 2020 at 20:36 dewddewd 17911 bronze badges 3
  • Since the wp_get_current_user() is not returning anything and you get a 401 when adding the permission callback, my guess would be that you are not logged in when trying to POST data to your endpoint. If you return the value from is_user_logged_in() in your endpoint I guess you would get a false value. It also seems like you really should use GET here since you are trying to retrieve data, not create anything. You could also try some of the answers in this question: stackoverflow.com/questions/38371754/… – Cyclonecode Commented Sep 19, 2020 at 21:46
  • 1 Here I think is the solution to your problem, you probably forgot about the authentication and nonces: stackoverflow.com/a/42469456/1047662 Here is another link also related to this: wordpress.stackexchange.com/questions/295471/… – Cyclonecode Commented Sep 19, 2020 at 21:54
  • 1 @Cyclonecode you're right. Looks like I need to use a solution similar to this: stackoverflow.com/a/57032303/2298108. Btw, definitely logged in and I'm actually going to be creating/ updating data so POST is correct. I'm just using this basic example t show I couldn't get the user id via REST for something else I need. Thx bud. – dewd Commented Sep 19, 2020 at 23:38
Add a comment  | 

2 Answers 2

Reset to default 5

This is happening because you are not using nonces. Because you have not provided a nonce with the request, Wordpress is treating you as if you are an unauthorized/non-logged in user. This is because wordpress has no way of knowing/validating the users state.

To get this working, you will have to generate a nonce like so:

wp_create_nonce( 'wp_rest' )

and provide it to the app that is making the rest call. Once your app has the nonce value, you would add it to the rest request like so:

headers: {
    'X-WP-Nonce': nonce,
}

Once you've done this, Wordpress will be able to use the nonce to properly validate the user and conditional checks for permissions will work as expected.

Edit

Per your comment, I thought I would elaborate as this information may be useful for anyone coming across this in the future.

A nonce is defined as a number used once. How wordpress uses them, and why it's required is the following:

"A nonce is a "number used once" to help protect URLs and forms from certain types of misuse, malicious or otherwise. WordPress nonces aren't numbers, but are a hash made up of numbers and letters. Nor are they used only once, but have a limited "lifetime" after which they expire. During that time period the same nonce will be generated for a given user in a given context. The nonce for that action will remain the same for that user until that nonce life cycle has completed.

WordPress's security tokens are called "nonces" despite the above noted differences from true nonces, because they serve much the same purpose as nonces do. They help protect against several types of attacks including CSRF, but do not protect against replay attacks because they aren't checked for one-time use. Nonces should never be relied on for authentication or authorization, access control. Protect your functions using current_user_can(), always assume Nonces can be compromised.

For an example of why a nonce is used, an admin screen might generate a URL like this that trashes post number 123."

The TLDR is that nonces are used in conjunction with user authentication cookies provided in the rest request, just like with any server side request. Nonces just provide an additional layer that can be relied on to ensure the user is who they say they are. It's not a replacement for authentication per se.

For a comprehensive description, see https://codex.wordpress.org/WordPress_Nonces#:~:text=WordPress%20nonces%20aren't%20numbers,user%20in%20a%20given%20context.

Use the following logic

This is a way to manually check the loggedin user cookie and that way getting the logged in user.

Make sure you send the cookies of wordpress logged in user page in the Rest API request.

function get_current_user_data_manually(WP_REST_Request $request) {
// Retrieve the cookies from the request
if (!isset($_COOKIE[LOGGED_IN_COOKIE])) {
    return new WP_Error('no_cookie', 'Authentication cookie is missing.', array('status' => 401));
}

$cookie = $_COOKIE[LOGGED_IN_COOKIE];
$user_id = wp_validate_auth_cookie($cookie, 'logged_in');

if (!$user_id) {
    return new WP_Error('invalid_cookie', 'Authentication cookie is invalid.', array('status' => 403));
}

$current_user = get_user_by('id', $user_id);

if (!$current_user) {
    return new WP_Error('no_user', 'No user found for the given ID.', array('status' => 404));
}

// Return user data
return array(
    'ID' => $current_user->ID,
    'username' => $current_user->user_login,
    'email' => $current_user->user_email,
    'display_name' => $current_user->display_name,
    'roles' => $current_user->roles,
);
}

Note: This method will not be applicable if you are making the API request totally outside of wordpress environment. Like a standalone react app for example.

本文标签: No user found when using REST API