【发布时间】:2022-11-05 05:14:34
【问题描述】:
我有一个带有 Oauth 2.0 的 Google Calendar API 设置。我的网络应用程序有教师和学生。老师的创作活动,学生可以参加。我已经为所有用户创建了功能,以将他们的 Google 帐户与日历 API 的权限连接起来,教师可以 create events 并成功删除它们,该事件已从他们的 primary 日历中添加和删除。
为此,我不需要老师的帐户电子邮件地址。当他们授权我的应用程序 API 访问他们的帐户时,我得到一个具有 CALENDAR_EVENTS 范围的令牌,我可以单独使用它在他们的日历中创建一个事件。令牌内容是这样的:
{
"access_token":"[redacted]",
"expires_in":3599,
"refresh_token":"[redacted]",
"scope":"https:\/\/www.googleapis.com\/auth\/calendar.events",
"token_type":"Bearer",
"created":1656203897
}
我也有来自具有类似令牌的学生的 Oauth 2 授权。当学生加入活动时,我想update the event 并将该学生添加为与会者。他们在我的应用上使用的帐户的电子邮件地址可能与他们为我的应用授权 Oauth 2 时使用的 Google 帐户不匹配。所以,我需要一种方法来获取他们授权的帐户的电子邮件地址。
这是将授权用户添加为与会者的正确过程吗?我四处寻找获取用户帐户信息的方法,发现大多是过时的信息。我更喜欢使用 PHP Google SDK 中的 Google_Client() 对象,甚至更好的是 Google_Service_Calendar() 对象。
如前所述,我只要求Google_Service_Calendar::CALENDAR_EVENTS 范围。我是否需要添加更多范围才能获取此信息?我也找到了这个Google Identify documentation,但不确定我是否需要这个。
我尝试使用另一种方法来尝试使用 GET 请求的 oauth2 API:
<?php
$resp = file_get_contents("https://www.googleapis.com/oauth2/v3/userinfo?access_token=[redacted]");
print($resp);
?>
Warning: file_get_contents(https://www.googleapis.com/oauth2/v3/userinfo?access_token=[redacted]): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized in /path/to/api_user.php on line 4
编辑:
阅读第一个答案后,我阅读了documentation here 并使用了文档中提供的 PHP 代码:
require_once 'vendor/autoload.php';
// Get $id_token via HTTPS POST.
$client = new Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$userid = $payload['sub'];
// If request specified a G Suite domain:
//$domain = $payload['hd'];
} else {
// Invalid ID token
}
代码的第一部分工作正常,我可以使用 client_id 获取 $client 对象。但是,它没有说明从哪里获得 $id_token。我看到from this post id_token 是 Oauth2 响应中的一个字段,但我的响应 JSON 不包含此字段。
【问题讨论】:
标签: php google-oauth google-calendar-api