Tmeister / wp-api-jwt-auth

A simple plugin to add JSON Web Token (JWT) Authentication to WP REST API
GNU General Public License v2.0
546 stars 160 forks source link

"rest_forbidden" error when called from script within site #260

Closed robhadfield closed 9 months ago

robhadfield commented 1 year ago

Hi all - hoping someone can help.

If I generate a token and call from Postman or CURL everything works as expected - but if I call the endpoint from a script within the domain it fails authentication.

For example, just pasting the script into a html file at the root fails but the same script works from another domain.

Request:

fetch("https://my-site/wp-json/darts/v1/venues", {
    headers: { Authorization: "Bearer my-token-string" }
  })
  .then((response) => response.json())
  .then((data) => console.log(data));

Response:

{
    "code": "rest_forbidden",
    "message": "Sorry, you are not allowed to do that.",
    "data": {
        "status": 401
    }
}
nathanbrnrd commented 1 year ago

@robhadfield could you find a solution to this problem?

I have the same issue. Working from localhost and sending request to my custom local domain, evrything works fine but when calling the script from the same domain, I have the same error.

robhadfield commented 1 year ago

@nathanbrnrd Kind of - although I stopped using jwt.

I use axios for my API calls so I now use the built in WordPress API helper... This will then use the current user's auth level to make the queries. You send the user nonce as a header.

Something like:

xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);

I'm not on the right machine at the moment but will post a code snippet later.

Would that approach wrk for you?

nathanbrnrd commented 1 year ago

Hey @robhadfield Thanks for your answer!

Actually I reverted the authentification process to the native cookie authentification system, the one you described with the X-WP-Nonce! I develop a little UI with angular and while the development environment is served on localhost:4200 and send requests to my-custom-local-domain.local, it wasn't possible to use the X-WP-Nonce header out-of-the-box.

I'll need to investigate more the JWT process and see if that would be a relevant option for production as my app is served from the same origin and is a script within the site (do not know yet which one is the culprit). Moreover, with the JWT you need to send the user credentials when you want to get a token which is not relevant in my case because the app is embed in a admin setting page (so the user has already to be logged in as admin to be there in the first place).

For this use case, I might keep the JWT while developing on localhost and the X-WP-Nonce when serving the app from the same origin / within the site.