Search code examples
phpwordpresswordpress-rest-api

How to get user from REST API using cookie-based auth


Quick context: I'm evaluating possible solutions for authentication for some custom restful endpoints for our WIP headless WordPress site.

What I'm trying to achieve is making is_user_logged_in return true in my custom endpoint using cookie based auth.


Here's my current setup and here's what I've tried.

I have the following in functions.php

// create an endpoint for getting a nonce
function get_nonce() {
    return new WP_REST_Response(array('nonce' => wp_create_nonce( 'wp_rest' )));
}
add_action( 'rest_api_init', function () {
    register_rest_route('my-site', 'nonce', array(
        'methods' => 'GET',
        'callback' => __NAMESPACE__ . '\get_nonce'
    ));
} );
function get_orders() {
    if ( !is_user_logged_in() ) {
        return new WP_Error( 'not_authorized', 'You are not logged in', array('status' => 401) );
    }

    $orders = // ...

    return new WP_REST_Response($orders);
}
add_action( 'rest_api_init', function () {
    register_rest_route( 'my-site', 'orders', array(
        'methods' => 'GET',
        'callback' => __NAMESPACE__ . '\get_orders',
    ));
} );

So in summary this creates two endpoints:

  • /wp-json/my-site/nonce to generate a nonce
  • /wp-json/my-site/orders to pull some user data

What I do is:

  1. call GET /wp-json/my-site/nonce to grab the nonce
  2. call GET /wp-json/my-site/orders?_wpnonce=thepreviousnonce

What I get back is this error:

{
  "code": "rest_cookie_invalid_nonce",
  "message": "Cookie nonce is invalid",
  "data": {
    "status": 403
  }
}

I'm just using the browser and URLs to make the requests and I've checked that the cookies are being included with each request.

What am I missing? Why am I getting the 403?


Solution

  • the nonce you're generating is invalid. making nonce in rest context doesnt work because that also needs a nonce! what it returns is a logged out user nonce. if you need a token based authentication i recomend JWT wp rest auth documentation