Can't Validate Google Access Token (wrong numb

2019-05-17 05:25发布

问题:

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?

回答1:

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.



回答2:

I used access_token instead of id_token when passing it in POST



回答3:

I had the same issue and didn't get any fix. I had to change the way I was fetching user info. Instead of using $client->verifyIdToken(); I have used the service class this way :

$authService=new Google_Service_Oauth2($client);
    if($client->getAccessToken()){
        $data=$authService->userinfo->get();
    }

So, to get the current user email, I used $email=data['email'];.

Hope this works!