Maciej Trzciński
Maciej Trzciński

Reputation: 181

Wordpress: Problem with rest_cookie_invalid_nonce

When I send rest request to the wp-rest by:

$response = wp_remote_post( $url, array(
  'method' => 'POST',
  // 'headers' => $headers,
  'httpversion' => '1.0',
  'sslverify' => false,
  'body' => json_encode( array(
    'data' => $field,
  ))
));

Unfortunately, I get 403 error:

{"code":"rest_cookie_invalid_nonce","message":"Kodem jednorazowy z ciasteczka jest nieprawid\u0142owy","data":{"status":403}}

Maybe someone knows how to resolve this issue?

Upvotes: 2

Views: 3899

Answers (1)

Sean Conklin
Sean Conklin

Reputation: 11

When you use wp_remote_... your cookies are not included. WordPress REST API uses the _wpnonce value to validate your session against the wp_rest keyword and your cookie values. To fix this, your options are to either switch to an AJAX browser call to the endpoint from the same browsing session, or you can stick with the remote REST API request and include your cookies in it like this:

$cookies = [];
foreach( $_COOKIE as $name => $value ) {
    $cookies[] = new WP_Http_Cookie(
        [ 'name' => $name, 'value' => $value ]
    );
}
$args = [
    'body' => [],
    'cookies' => $cookies,
    'headers' => [ 'Content-type' => 'application/json' ],
];
$url = get_rest_url() . 'endpoint/v1/endpoint/';
$response = wp_remote_get( $url, $args );

Upvotes: 1

Related Questions