获取令牌的过期时间戳


Get expiration timestamp of token

我正在使用Google api php客户端来验证从android应用程序发送的idToken。我以这种方式验证它:

$client = new Google_Client();
if (isset($token)) {
   $client->setClientId("xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com");
   try{
            $userId = $client->verifyIdToken($token)->getUserId();
  }catch(Exception $e){
      ...

Google_Client类调用,然后Google_OAuth2在方法 verifySignedJwtWithCerts 中实际完成验证的类。

我不仅想获取 userId,还想获取令牌的过期时间戳。我虽然我可能会在Google_OAuth2中制作一种方法来获取它,然后在Google_client中调用Google_Oauth2中的第一个方法的方法,但它不起作用。怎么可能呢?

$client->getAccessToken() 函数将返回一个 json 编码的字符串,该字符串不仅包含访问令牌,还包含创建的时间戳及其生命周期。因此,要获取过期时间戳,只需将生命周期添加到创建的时间,如下所示:

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

如果您已经拥有访问令牌并且不知道它是何时创建的,TokenInfo API 将为您提供用户 ID、到期前的剩余时间(以秒为单位)以及许多其他信息。谷歌开发者网站上有一个页面更详细地解释了这一点。

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

你可以试试这个:

$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);
}

希望这有帮助!