Home > Enterprise >  Can't acces the Wordpress Api from a React website
Can't acces the Wordpress Api from a React website

Time:03-18

I come to you in a time of great need. I've spent like a week on this and still can't figure it out. Please help.

Here is what I want to do:

I've got a WordPress website (http://test/test.wp/) on which you can do the following API call right in the browser when you are logged in:

$.ajax({
  url: 'http://test/test.wp/wp-json/wp/v2/users/me',
  method: 'GET',
  beforeSend: function(xhr){
    xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
  }
}).done(function(response){
  console.log(response);
}).fail(function(response){
  console.log( response.responseJSON.message );
});

And it works just fine. You get a Json about the current user (I just need the ID)

Now, I got another website (subdomain) written in React (http://app.test) and I am trying to pretty much do the same GET request to WordPress to grab the ID of the currently logged in User.

The sites are interconnected and I am sort of trying to imitate a SSO between WordPress and React by simply grabbing the ID of the currently logged in user in WordPress and using it in the react subdomain

To achieve this I've taken care of the CORS so I can make GET request from React to WordPress with no problems. I also shared my WordPress wordpress_logged_in_cffb670352ad40cd796ad890d27ee701 cookie with the React subdomain so I've got access to that (which, from what I understand is the only cookie needed to keep you authenticated)

So, with all of that said why is my request from React failing?

    Axios({
    method: 'get',
    url: 'http://test/test.wp/wp-json/wp/v2/users/me',
    headers: {
        'X-WP-Nonce': '659cbfeec0', // <= It's needed to use the WP Api and it's correct. I mannually grabed it from WP with wpApiSettings.nonce

        withCredentials: true, // <= From what I understand is the only thing needed to send the `wordpress_logged_in_cffb670352ad40cd796ad890d27ee701`  cookie ???
    },
})
    .then(response => console.log(response))
    .catch(err => console.log(err));

So why then the answer that I get is a 403 (Forbidden)?:

    code: "rest_cookie_invalid_nonce"
data: {status: 403}
statusText: 'Forbidden'
message: "Cookie verification failed"

You can say that the answer is in the response that I get, but I really have no idea why that's the case.

Please help.

Desperate Coder.

CodePudding user response:

I was passing the 'with-Credentials' in the Headers and was not sending the cookies in the request because of that.

The correct way of doing it is:

Axios.get(
            'http://test/test.wp/wp-json/wp/v2/users/me',
            {
                withCredentials: true,
                headers: { 'X-WP-NONCE': 'Your_Nonce' },
            }
        )
  • Related