PHP中Google ID Token缺少信息



我使用Google OAuth 2.0作为我的服务器端web应用程序,使用PHP 5.4.45和Google API客户端PHP库2.1.1版。

我可以成功地将authorization coderefresh_tokenaccess_tokenid_token交换,我可以正确地验证id_token并从中提取用户数据,但缺少一些信息。

我请求了profileemail作用域,这两个作用域都能在同意屏幕和用户的应用程序设置中正确显示,但是,虽然电子邮件可用,但id_token中缺少与profile作用域相关的所有声明(名称、图片等)

我尝试过不同的用户,但问题仍然存在。

这是我正在使用的代码(仅用于测试目的):

require_once 'php/libs/google_api_client_library/vendor/autoload.php';
if(!isset($_GET['code'])){
die("code parameter not set");
}else{
//exchange 'code' with access token, refresh token and id token
$data = array(
'code' => $_GET['code'],
'client_id' => $MY_CLIENT_ID,
'client_secret' => $MY_CLIENT_SECRET,
'redirect_uri' => 'https://www.mywebsite.com/oauth2callback.php',
'grant_type' => 'authorization_code'
);
$options = array(
'http' => array(
'header'  => "Content-type: application/x-www-form-urlencodedrn",
'method'  => 'POST',
'content' => http_build_query($data)
)
);
$response = file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create($options));
if($response){
$tokens = json_decode($response);
$client = new Google_Client();
//validate idToken and get user info
$idtoken = $client->verifyIdToken($tokens->id_token);
echo "<h1>ID_TOKEN</h1>";
var_dump($idtoken);
}
}

最奇怪的是,它以前工作正常,然后突然开始这样,我不记得对这个代码做过任何更改。

我还注意到,这种情况只发生在PHP的服务器端,因为JavaScript API客户端库一切都很好。

你知道为什么会发生这种事吗?

如果您需要任何进一步的信息,请告诉我,并提前感谢!

我不知道到底是什么问题,但在互联网上找到的一些例子的帮助下,我使用了Google_Service_Oauth2类并编辑了我的代码,如下所示:

require_once 'php/libs/google_api_client_library/vendor/autoload.php';
if(!isset($_GET['code'])){
die("code parameter not set");
}else{
$client = new Google_Client();
$client->setClientId($MY_CLIENT_ID);
$client->setClientSecret($MY_CLIENT_SECRET);
$client->setApplicationName('MyApplicationName');
$client->setRedirectUri('https://www.mywebsite.com/oauth2callback.php');
$oauth = new Google_Service_Oauth2($client);
$client->authenticate($_GET['code']); //exchange 'code' with access token, refresh token and id token
$accessToken = $client->getAccessToken();
$userData = $oauth->userinfo->get(); //get user info
echo "<h1>USER DATA</h1>";
var_dump($userData);
}

现在一切都很好!

最新更新