Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress REST API Authentication Using Fetch

I'm attempting to use cookie authentication for WordPress REST API access using the Fetch API, however the auth is failing with the following error.

403: Cookie Nonce is Invalid

I'm using the following script to connect to the API.

const headers = new Headers({
   'Content-Type': 'application/json',
   'X-WP-Nonce': WPAPI.nonce
});  

fetch(WPAPI.root + 'my-endpoint/upload/', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
})

When I switch from using Fetch to XMLHttpRequest it works as expected.

let request = new XMLHttpRequest();
request.open('POST', WPAPI.root + 'my-endpoint/upload/', true);
request.setRequestHeader('X-WP-Nonce', WPAPI.nonce);
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));

Is it possible there an issue with the way headers are being sent in the Fetch method?

like image 479
Darren Cooney Avatar asked Sep 13 '17 18:09

Darren Cooney


People also ask

How do I fetch data from API in WordPress?

If you want to use the Fetch API with WordPress, you simply have to call the fetch function in your JavaScript code. Follow that function with a . then handler to access the content. You can then display it on your website or in your web application.

What method does the WordPress REST API use for authentication?

Cookie authentication is the standard authentication method included with WordPress. When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user. However, the REST API includes a technique called nonces to avoid CSRF issues.

Is fetch API same as REST API?

The Fetch API is a simpler, easy-to-use version of XMLHttpRequest to consume resources asynchronously. Fetch lets you work with REST APIs with additional options like caching data, reading streaming responses, and more. The major difference is that Fetch works with promises, not callbacks.


1 Answers

WordPress nonce authentication requires the use of cookies and by default Fetch doesn't send those along. You can use the credentials option to make this work:

fetch(endpoint, {
  credentials: 'same-origin'
})

https://github.com/github/fetch#sending-cookies

like image 54
BrechtVds Avatar answered Sep 25 '22 07:09

BrechtVds