无法验证 Google 访问令牌(段数错误)

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

我的代码很简单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";
}

我收到以下错误:

<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...')

有人知道这是为什么吗?

我在 POST

中传递它时使用 access_token 而不是 id_token

回答这个问题是因为另一个问题太短而且含糊不清。

不传递 profile.getId() 返回的 ID,而是传递 googleUser.getAuthResponse().id_token 返回的 ID 作为您的 id_tokenPOSTid 字段请求您用来将用户的 ID 发送到您的服务器)。

给任何开发人员的一个重要提示:如果你认为你做了你应该做的一切,并且对他们有用,但对你不起作用,那么你没有做你应该做的一切.

我遇到了同样的问题,但没有得到任何修复。我不得不改变获取用户信息的方式。我没有使用 $client->verifyIdToken();,而是通过这种方式使用了服务 class:

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

因此,为了获取当前用户的电子邮件,我使用了 $email=data['email'];

希望这有效!