获取令牌的到期时间戳

时间:2013-09-05 13:07:55

标签: php oauth-2.0 token google-oauth google-client

我正在使用Google api php client来验证从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中第一个方法的方法,但它不起作用。怎么可能呢?

1 个答案:

答案 0 :(得分:0)

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

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

如果您已经拥有访问令牌并且不知道它何时被创建,则TokenInfo API将获取用户ID,剩余时间(以秒为单位)到期,以及许多其他信息。有一个page on the Google Developers site可以更详细地解释这一点。

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

希望这有帮助!

相关问题