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
544 stars 160 forks source link

Not allowed to view drafts #300

Open swif-nl opened 3 months ago

swif-nl commented 3 months ago

I am building a headless Wordpress website (VueJS). Data is loaded via the REST API.

Now, I need to enable the preview-functionality. I installed this plugin. When I hit the preview button in Wordpress it opens a new tab for the specific page and adds these params to the URL: ?preview_id=11&preview_nonce=d778b8981f&preview=true&acf_format=standard

I add these params to the URL for the REST API call to retrieve the page-data.

Default: http://localhost:8888/wp-json/wp/v2/pages/13

Draft: http://localhost:8888/wp-json/wp/v2/pages/13?preview_id=11&preview_nonce=d778b8981f&preview=true&acf_format=standard

Of course, I need some authorization to be able to load the draft version. In order to do that I can successfully request a JWT token and add this to the draft-page request. However, the response I get tells me "you are not allowed to preview drafts". The response is a HTML error page, and not a JSON response as I would expect.

When I test a (no-draft) request in Postman, I add the JWT authorization token and the API returns the requested data. When I change a character in the JWT token it returns a JWT error. So I know my JWT token is valid and recognized by Wordpress.

What could be the cause of this issue?

swif-nl commented 3 months ago

I found out that it had something to do with the nonce-validation. Wordpress uses the wp_get_session_token() function to generate a nonce. In my setup there are actually two sessions (the backend login and the frontend/JWT login). This means the session_tokens are different, and therefore the nonces are different. When I bypass the nonce validation, the draft data is loaded (I also added a status=draft param):

http://localhost:8888/wp-json/wp/v2/pages/13?preview_id=13&_wpnonce=d778b8981f&preview=true&acf_format=standard&status=draft

Now I am looking for a sollution to solve the nonce validation problem.

  1. Not using the wp_get_session_token() function in nonce generating / validation
  2. Finding a way to use the same session_token.

Any suggestions?