I'm trying to test borrowing a nonce from my browser session so that I can use it elsewhere, namely in my npm dev environment.
I took a nonce passed into an open Chrome browser session, put it in a get request header for "X-WP-Nonce" in Postman and got back "Cookie nonce is invalid":
I also tried entering the nonce value without surrounding " "
Does anyone know why this request is failing?
Added
I don't believe it should matter but just in case, here is the callback for the /auth
route handler:
public function authCallback(\WP_REST_Request $request) : void {
$this->isAdminOrRejectionResponse();
wp_send_json([
'success' => "You have access to wp_get_current_user()"
]);
}
protected function isAdminOrRejectionResponse() {
if (current_user_can('administrator') === false) {
wp_send_json(['error' => 'You do not have Administrator credentials.']);
}
}
I'm trying to test borrowing a nonce from my browser session so that I can use it elsewhere, namely in my npm dev environment.
I took a nonce passed into an open Chrome browser session, put it in a get request header for "X-WP-Nonce" in Postman and got back "Cookie nonce is invalid":
I also tried entering the nonce value without surrounding " "
Does anyone know why this request is failing?
Added
I don't believe it should matter but just in case, here is the callback for the /auth
route handler:
public function authCallback(\WP_REST_Request $request) : void {
$this->isAdminOrRejectionResponse();
wp_send_json([
'success' => "You have access to wp_get_current_user()"
]);
}
protected function isAdminOrRejectionResponse() {
if (current_user_can('administrator') === false) {
wp_send_json(['error' => 'You do not have Administrator credentials.']);
}
}
Share
Improve this question
edited Sep 18, 2019 at 9:19
Sean D
asked Sep 18, 2019 at 9:14
Sean DSean D
3878 silver badges21 bronze badges
1
- 2 Sending the nonce only allows the REST API to use the browser's cookies to authenticate the user. It's not sufficient to authenticate on its own. If you're trying to send the request from postman you need to also include a valid cookie. – Jacob Peattie Commented Sep 18, 2019 at 9:26
1 Answer
Reset to default 2For remote apps (cURL, Postman, etc.), or when not using the browser, you should use an authentication plugin like Application Passwords instead of sending the cookies.
But if you'd rather send the cookies, then copy and send the WordPress logged-in cookie named wordpress_logged_in_<hash>
. Example in cURL:
curl -H "X-WP-Nonce: <nonce>" -X POST https://example/wp-json/wp/v2/posts -d "Data here" -b wordpress_logged_in_<hash>=<cookie value>
Note that WordPress saves the user's login data (username and hashed data) in a cookie named wordpress_logged_in_<hash>
(but you can change it using the LOGGED_IN_COOKIE
constant).
Also, in the above (cURL) example, I used the X-WP-Nonce
header to send the cookie nonce.
UPDATE: Added a screenshot for (locating and copying) the cookie in Chrome: