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.
2 Answers
Reset to default 5This 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
版权声明:本文标题:No user found when using REST API 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736305755a1932702.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
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 fromis_user_logged_in()
in your endpoint I guess you would get a false value. It also seems like you really should useGET
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