Google OAuth令牌过期

时间:2016-09-05 05:23:30

标签: php oauth google-plus-signin

我有这个代码在我第一次登录时工作正常,但是如果页面处于打开状态并且我没有退出该会话,我会收到以下消息,我必须重新启动浏览器以获取我的页面再次。如何让令牌自动刷新?

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.'...

这是代码

<?php

require_once __DIR__.'/gplus-lib/vendor/autoload.php';

const CLIENT_ID = 'CLIENT_ID';
const CLIENT_SECRET = 'CLIENT_SECRET';
const REDIRECT_URI = 'REDIRECT_URI';

session_start();

$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes('email');

$plus = new Google_Service_Plus($client);

if (isset($_REQUEST['logout'])) {
   session_unset();
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $me = $plus->people->get('me');

  // Get User data
  $id = $me['id'];
  $name =  $me['displayName'];
  $email =  $me['emails'][0]['value'];
  $profile_image_url = $me['image']['url'];

} else {
  // get the login url   
  $authUrl = $client->createAuthUrl();
}

?>
<div>
if (isset($authUrl)) {
    echo "<a class='login' href='" . $authUrl . "'><img src='gplus-lib/signin_button.png' height='50px'/></a>";
} else { ?>

<!-- Some HTML -->

<?php
}
?>
</div>

2 个答案:

答案 0 :(得分:0)

您无法捕获错误'Google_Auth_Exception'并生成新令牌?

如果您的测试是在登录前调用Service并使用该令牌进行google,则可以知道此令牌是否已过期,并在调用失败时生成新令牌。

答案 1 :(得分:0)

这是授权代码流程。在请求authCode时,您还必须请求 Offline_Access 声明。

根据该声明,您将获得刷新令牌以及访问令牌。然后,每次访问令牌到期时,该刷新令牌都可用于获取新令牌。

因此,您可能在请求auth_Code的位置,您必须要求另一个为您提供刷新令牌的范围。

对于测试,您可以使用Postman应用程序。当您要求不同的范围时,这将让您了解收到的信息。