【问题标题】:Get expiration timestamp of token获取token的过期时间
【发布时间】:2013-09-05 13:07:54
【问题描述】:

我正在使用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 中的第一个方法,但它没有用。怎么可能做到?

【问题讨论】:

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


    【解决方案1】:

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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2018-12-22
      • 2018-11-19
      • 2019-03-04
      • 2021-04-07
      • 1970-01-01
      • 2016-04-15
      • 2011-09-20
      • 2021-12-29
      相关资源
      最近更新 更多