Search code examples
phpgoogle-apijwtgoogle-api-php-clientgoogle-api-client

Can't Validate Google Access Token (wrong number of segments)


I have very simple code directly from Google's website

$client = new Google_Client(['client_id' => $CLIENT_ID]);

$payload = $client->verifyIdToken($id_token);

if ($payload) {
  $userid = $payload['sub'];
  echo $userid;
} else {
  // Invalid ID token
  echo "error";
}

I get the following error(s):

<b>Fatal error</b>:  Uncaught exception 'UnexpectedValueException' with message 'Wrong number of segments' in /../vendor/firebase/php-jwt/src/JWT.php:79
Stack trace:
#0 /../vendor/google/apiclient/src/Google/AccessToken/Verify.php(103): Firebase\JWT\JWT::decode('ya29.GlzbAwEXTe...', '-----BEGIN PUBL...', Array)
#1 /../vendor/google/apiclient/src/Google/Client.php(713): Google_AccessToken_Verify-&gt;verifyIdToken('ya29.GlzbAwEXTe...', '1074005180734-g...')
#2 /../pages/auth/session.php(7): Google_Client-&gt;verifyIdToken('ya29.GlzbAwEXTe...')

Does anyone know why this is?


Solution

  • Answering this question because the other one is too short and vague.

    Instead of passing the ID returned by profile.getId(), pass the one returned by googleUser.getAuthResponse().id_token as your id_token (the id field of the POST request you use to send the user's id over to your server).

    A great tip for any developer: If you think you did everything you were supposed to do, and it is working for them, but it is not working for you, then you did not do everything you were supposed to do.