【问题标题】:oauth2 access token expireoauth2 访问令牌过期
【发布时间】:2015-05-13 01:48:25
【问题描述】:
<?php
session_start();

require_once realpath(dirname(__FILE__) . '/Google/src/Google/autoload.php');

/************************************************
  ATTENTION: Fill in these values! Make sure
  the redirect URI is to this page, e.g:
  http://localhost:8080/user-example.php
 ************************************************/
 $client_id = 'xxxxx-1l76cd2vi4ik5oqm5s20nj965riu4hum.apps.googleusercontent.com';
 $client_secret = 'secret';
 $redirect_uri = 'http://www.audit.polydevs.co.uk/oauth2callback.php?login';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes('email');

/************************************************
  If we're logging out we just need to clear our
  local access token in this case
 ************************************************/

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
  header("Location: login.php");
}

if (isset($_REQUEST['logoutInvalid'])) {
    unset($_SESSION['access_token']);
    header("Location: login.php?invalid");
}

/************************************************
  If we have a code back from the OAuth 2.0 flow,
  we need to exchange that with the authenticate()
  function. We store the resultant access token
  bundle in the session, and redirect to ourself.
 ************************************************/
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 we have an access token, we can make
  requests, else we generate an authentication URL.
 ************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

/************************************************
  If we're signed in we can go ahead and retrieve
  the ID token, which is part of the bundle of
  data that is exchange in the authenticate step
  - we only need to do a network call if we have
  to retrieve the Google certificate to verify it,
  and that can be cached.
 ************************************************/
if ($client->getAccessToken()) {
  $_SESSION['access_token'] = $client->getAccessToken();
  $token_data = $client->verifyIdToken()->getAttributes();
}

if($client->isAccessTokenExpired()) {
  echo 'Access Token Expired'; // Debug
  $client->authenticate;
  $newAccessToken = json_decode($client->getAccessToken());
  $client->refreshToken($newAccessToken->refresh_token);
}

if (strpos($client_id, "googleusercontent") == false) {
  echo missingClientSecretsWarning();
  exit;
}

if (isset($_REQUEST['login'])) {
    if (isset($authUrl)) {
        header('Location:'.$authUrl);
    } else {
        require_once('func/connect.php');
        $query = "SELECT * FROM users WHERE email = ?";
        $stmt = $db->prepare($query);
        $stmt->bindValue(1, $token_data['payload']['email']);
        $stmt->execute();

        $count = $stmt->rowCount();

        if ($count > 0) {           
            header('Location: index.php');
        } else {
            $plus = new Google_Service_Plus( $client );
            $me = $plus->people->get('me');

            $query = "INSERT INTO users (name,email,role) VALUES(?,?,?)";
            $stmt = $db->prepare($query);
            $stmt->bindValue(1, $me['displayName']);
            $stmt->bindValue(2, $token_data['payload']['email']);
            $stmt->bindValue(3, 'regular');
            $stmt->execute();

            header('Location: index.php');
        }
    }
}

特别是这里

if($client->isAccessTokenExpired()) {
  echo 'Access Token Expired'; // Debug
  $client->authenticate;
  $newAccessToken = json_decode($client->getAccessToken());
  $client->refreshToken($newAccessToken->refresh_token);
}

一旦我的令牌过期,我将无法退出或访问任何网页,因为它们需要一个有效的令牌..

我也不能登录,因为这也需要!

或者,我可以禁用它吗!

编辑

我很抱歉,我累了,假设每个人都知道我在说什么。问题是当访问令牌过期时,我可以取消设置 $_SESSION['access_token'] 并强制重新登录在(主要问题)或有一种方法只是刷新/禁用令牌/过期,这样它就不会妨碍用户正在进行的任何进程。

【问题讨论】:

  • 您能否提供更多详细信息来描述您的问题(用英文,而不仅仅是代码)?就目前而言,我必须做出许多推论才能知道您在问什么。没有我那么耐心的人可能会找到你想要的答案。
  • @jpaugh 我很抱歉,我很累,假设每个人都知道我在说什么。问题是当访问令牌过期时,我可以取消设置 $_SESSION[ 'access_token'] 并强制重新登录(主要问题)或有一种方法只是刷新/禁用令牌/过期,这样它就不会妨碍用户正在进行的任何进程。
  • 很抱歉没有得到您的答复。我自己只是模糊地意识到 OAuth。但我知道措辞得当的问题会得到更多关注。祝你好运!
  • 访问令牌过期它们通常是短暂的一个小时,您需要再次提示用户访问或将刷新令牌保存在某个地方,以便您可以使用它来获取新的访问令牌。这将取决于您的应用程序正在做什么,并且在它们不在线时您是否需要访问那里的数据。
  • @DalmTo 实际上client_id 被认为是公共知识。它用于构建登录 URL 和客户端 API。

标签: php google-oauth


【解决方案1】:

我建议您阅读有关 OAuth 的基本指南,以便您大致了解。

基本上服务器和客户端会通过一系列步骤来证明他们是他们所说的那个人。完成此操作后,服务器将发出一个短暂的access_token 和一个refresh_token。

然后您可以在所有 Api 请求中使用此 access_token。然而这个access_token 的生命周期是有限的。当它过期时,您必须将refresh_token 提供给服务器,它会发出另一个access_token

要使用 Google Api PHP 库执行此操作,请使用此代码

//$client is the GApi Client
if($client->isAccessTokenExpired()) {
    echo 'Access Token Expired'; // Debug
    $client->refreshToken('your_refresh_token');
}

【讨论】:

  • 天哪..我想我很累哈哈!我会重新生成一个新的秘密。谢谢你。所以,如果我按照逻辑采取这些步骤,我会没事的user logs in-&gt;refreshtoken is stored in db under their accesstoken-&gt;isaccesstokenexpired() runs, check db for refresh token with access token-&gt;setfrefreshtoken to db refreshtoken,我们可以开始了吗?
  • @danny123 我建议将 refresh_token 存储在用户 ID 下。这是因为access_token 会不断变化。但除此之外,是的,你很高兴。
  • 谢谢,我会把它存储在用户ID下。但是,我还有一个问题.. 抱歉 :P 如果我将其存储在用户 ID 下,即存储他们的姓名/电子邮件的位置,我将如何与 select 进行比较,如果令牌耗尽时他们的 token_data 将无法访问?
  • @Danny123 对于每个用户,只需存储与其关联的access_token 和refresh_token。然后,当您需要获取refresh_token 时,只需查询access_token 等于过期access_token 的用户表。所以 users 表会有 [user_id, user_email, access_token, refresh_token]。然后用SELECT * FROM users WHERE access_token='xxxxxxxxx'查询它
  • 我得到了它的工作,我假设没有访问令牌我无法使用他们当前的 $token_data,但事实并非如此,所以这很容易。谢谢。
猜你喜欢
  • 2017-04-11
  • 2019-03-10
  • 1970-01-01
  • 2012-11-30
  • 2020-11-27
  • 2020-08-19
  • 2016-01-04
  • 2018-07-17
  • 2016-02-15
相关资源
最近更新 更多