Get expiration timestamp of token

2.2k views Asked by At

I'm using Google api php client to verify the idToken sent from android app. I'm verifying it this way:

$client = new Google_Client();
if (isset($token)) {
   $client->setClientId("xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com");

   try{
            $userId = $client->verifyIdToken($token)->getUserId();
  }catch(Exception $e){
      ...

Google_Client class calls then Google_OAuth2 class where the verification is actually done in method verifySignedJwtWithCerts.

I'd like to get not only the userId, but also the expiration timestamp of the token. I though I might make a method in Google_OAuth2 to get it, and then method in Google_client which calls the first method in Google_Oauth2, but it didn't work. How could it be done?

1

There are 1 answers

0
CragMonkey On

The $client->getAccessToken() function will return a json-encoded string which contains not only the access token, but the timestamp it was created and its lifespan. So to get the expiration timestamp, simply add the lifespan to the time created, like this:

$access_tokens=json_decode($client->getAccessToken());
$expiration_timestamp=$access_tokens->created+$access_tokens->expires_in;

If you already have the access token and do not know when it was created, the TokenInfo API will get you the user id, remaining time (in seconds) until expiration, along with a host of other information. There is a page on the Google Developers site which explains this in more detail.

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={access_token}

You could try this:

$token_info=tokenInfo("{access token here}");

$user_id=0;
$expiration_timestamp=0;

if(!isset($token_info->error)){
    $user_id=$token_info->user_id;
    $expiration_timestamp=time()+$token_info->expires_in;
}

function tokenInfo($access_token){
    $url="https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=".$access_token;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output);
}

Hope this helps!