How can cookie/session authentication be used in wp-json fetch request?

I've written a /wp-json path like:

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin', 'foo', array(
    'methods' => 'GET',
    'callback' => function( $data ) {
      // if (!is_user_logged_in()) {
      //   return array();
      // }
      return array('dummy_data');
  ) );
} );

I can retreive the data using the es6-style fetch api like:

fetch('/wp-json/myplugin/foo', {credentials: 'include'})
  .then(res => res.json())
  .then(data => console.log(data))

This works dandy.

However, if I un-comment the if (!is_user_logged_in())... check, it never passes. I send the Cookie header in this request, but wordpress doesn't seem to do cookie/session-style authentication and is_user_logged_in() is never `true.

I know that there is the nonce mechanism, but this API will only ever be fetched from the wordpress site and I want to use the cookie/session mechanism.

How can I authenticate the user against their server session when the request is coming from the fetch or xhr API javascript mehanism?

Answers 1

  • After reading more, thanks to Jacob's link and more googling, it turns out that wordpress "nonces" aren't actually nonces. Nonces are to be used once, but wordpress "nonces" are allowed to be used an unlimited number of times for 2 "ticks", which normally means between 12 and 24 hours. These wordpress "nonces" are actually tied to a session and hence give me exactly what I want, since I can reuse the wordpress "nonce" for a period of time.

Related Questions