I have a Google Calendar API setup with Oauth 2.0. My web-application has teachers and students. Teachers create event and students can join. I have already created features for all users to connect their Google account with permissions for the calendar API, and teacher's can create events and delete them successfully, the event is added and removed from their primary
calendar.
To accomplish this, I do not need the teacher's account email address. When they authorize my apps API access to their account, I get a token with CALENDAR_EVENTS
scope and I can use it alone to create an event in their calendar. The token contents are like this:
{
"access_token":"[redacted]",
"expires_in":3599,
"refresh_token":"[redacted]",
"scope":"https:\/\/www.googleapis.com\/auth\/calendar.events",
"token_type":"Bearer",
"created":1656203897
}
I also have Oauth 2 authorization from the students with a similar token. When a student joins the event, I want to update the event and add that student as an attendee. The email address of their account on my app may not match their Google account used when they authorize Oauth 2 for my app. So, I need a way to get the Google email address of the account they authorized.
Is this the proper process for adding authorized user as an attendee? I have looked around for ways to get the user's account information and found mostly outdated information. I would prefer to use the Google_Client()
object from the PHP Google SDK, or even better the Google_Service_Calendar()
object.
As mentioned I only requested Google_Service_Calendar::CALENDAR_EVENTS
scope. Do I need to add more scope to get this information? I also found this Google Identify documentation but not sure if I need this.
I tried to use another method to try the oauth2 API with GET request:
<?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
EDIT:
After reading the first answer I have read the documentation here and using the PHP code provided in the docs:
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
}
The first part of the code works fine, I can get the $client
object with the client_id. However, It doesn't explain where to get the $id_token. I see from this post that the id_token is a field in the Oauth2 response, but my response JSON does not include this field.