Authenticate with WordPress cookie through API from a subdomain

I want to access the current logged in WordPress user in a separate Laravel installation.

WordPress is running as and I’ve got a subdomain with with the Laravel application (on another server but same domain).

I’m using the Native WordPress API and created an authentication route.

The issue:

When I access the /authenticate route directly, the user ID is returned and works correctly. But when I access the route through false is returned..

Things I’ve got working:

I’ve created an API request which returns the user id in an API call:

add_action( 'rest_api_init', function () {
  register_rest_route( '/authenticate', array(
    'methods' => 'GET',
    'callback' => 'authenticate',
  ) );
} );

The function looks like this:

$user_id = wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' );

The WP cookie is available on both the sub / main domain. I can see they are identical and toplevel.

define('COOKIE_DOMAIN', '');

Things I’ve tried:

  • Using wp_get_current_user() to retrieve the user, this seems to need a nonce. I experimented hours and hours with the nonce approach on many different ways, but I could not get this to work (false or 0 was returned). I understand this is due to restrictions of using a nonce from outside of WordPress.
  • Using the default native API approach to get the user, also needs the nonce.
  • Reading the manual, git repository & several articles / comments online.
  • Thinking about the OAuth approach, but I do not want users to login again as they are already logged in when they reach the tool.
  • Sending stuff like posts etc works without problems, so the API connection is not the problem.

I’m wondering if my approach is in the right direction. Hopefully someone can give me some guidance.

Read more here: Authenticate with WordPress cookie through API from a subdomain

Leave a Reply

Your email address will not be published. Required fields are marked *