REST API: wp_get_current_user not working on second call

After a whole day of digging and debugging through the super duper WordPress core functions, I realized the primary issue was that the session token used to create versus to verify the nonces were not equivalent. I tried different things, ending up calling the wp_set_auth_cookie method specifying the ‘logged_in’ cookie target.

Then, I fell on this topic: Extend WordPress (4.x) session and nonce where the guy seems to have a problem similar to mine.

I gave it a shot, adding the following action in my class:

/**
 * login_force_update_cookie - Specific action for force overriding the logged_in_cookie
 * when being in the AJAX registration context
 *
 * @param  {type} $logged_in_cookie description
 * @return {type}                   description
 */
public function login_force_update_cookie( $logged_in_cookie ) {
  if ( strstr( $_SERVER['REQUEST_URI'], 'toto/user/register' ) ) {
    $_COOKIE[LOGGED_IN_COOKIE] = $logged_in_cookie;
  }
}

And modifying a bit my code which now looks like the following:

wp_set_current_user($user_id);
if ( wp_validate_auth_cookie( '', 'logged_in' ) != $user_id )
{
   wp_set_auth_cookie( $user_id );
}

// Storing the regitration event for the user
$this->saveLoginEvent( $user_id );
$data = array(
   'user_id' => $user_id,
   'nonce'   => wp_create_nonce( 'wp_rest' ),
   'message' => 'user_created'
);
$response = rest_ensure_response( $data );

And that seems to have fixed the main issue, being the inconsistency between the nonces generated in the first AJAX response and verified during the second one. The issue with the wp_get_current_user returning 0 was that when the nonces are not ok, wordpress is setting the user to 0 by default.

Quite a tricky one, made my day as I learned a lot !

Thanks for your attention,