oauth-2.0 - 首次登录和授权后,Google+ OAuth API 存储和检索 token

标签 oauth-2.0 google-plus

我已阅读有关如何使用 Google API 的文档、示例和教程,我已经运行了一个显示您最新事件和信息的迷你应用程序,但我使用 session 来存储 token 。

我的问题是,如何从数据库中存储和检索 token ,以便当用户(已注册)单击“登录”时,它可以立即使用该 API,而无需重复授权?请注意,我使用该示例作为我的迷你应用程序的起点。

这是一个代码片段:

$client = new apiClient();
$client->setApplicationName(APP_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URL);
$client->setDeveloperKey(DEV_KEY);

$plus = new apiPlusService($client);
$google_userinfo = new apiOauth2Service($client);

$message = "";

// In a real application this would be stored in a database, and not in the session!
if (isset($_SESSION['token']))
  $client->setAccessToken($_SESSION['token']);

$_SESSION['token'] = $client->getAccessToken();

if (isset($_GET['code'])) {
   $client->authenticate();
  // In a real application this would be stored in a database, and not in the session!
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
...
 //Somewhere here, I added a function that ties $_SESSION['token'] to the user's info.
...
<form action="" method="post" id="form1" name="form1">
   <fieldset>
      <div id="main-url-section" style="width: 50%;margin: 0px auto;text-align: center;">
         <?php
            $authUrl = $client->createAuthUrl();
            print "<p><a class='login' href='$authUrl'>Log me in!</a></p>";
         ?>                                 
      </div>
    </fieldset>
</form>

十分感谢你的帮助!

问候,

约翰

最佳答案

如果您希望 Google 跳过已授权您的应用程序的人员的授权提示,请在顶部的配置块中添加以下代码:

$client->setAccessType("online");
$client-> setApprovalPrompt("auto");

此解决方案有一个问题:当您完成 OAuth 舞蹈时,您不会收到刷新 token 。这意味着您的用户每次访问 token 过期时都会被重定向到 Google 的身份验证服务以获取新的。这将大约每小时发生一次。

背景信息

默认情况下,PHP 客户端库配置为提供 offline access .您可以在 source code 中看到这一点.启用此模式后,OAuth 流将产生 refresh token可用于根据需要请求新的访问 token 。你甚至可能没有注意到这种情况的发生。 PHP 客户端库会为您处理大部分工作。

不过,这个刷新 token 是有代价的。您有责任存储它。如果您丢失了它,您的用户必须重新授权您的应用程序,以便向您发出另一个应用程序。您存储它的方式在很大程度上取决于您的实现细节。如果您可以使其足够持久, session 数据是一种合理的方法。

关于oauth-2.0 - 首次登录和授权后,Google+ OAuth API 存储和检索 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10101551/

相关文章:

spring - 在 Spring Security OAuth2 中使用用户名密码授权中的刷新 token 请求新的访问 token

Android 谷歌 API Java 客户端 com.google.api.client.auth.oauth2.draft10

ios - 适用于 iOS 的 Google OAuth 2.0 没有返回到我的应用程序

c++ - 如何使用 QOAuth2AuthorizationCodeFlow 和 QOAuthHttpServerReplyHandler 设置 redirect_uri

rest - 如何使用 OAuth2RestTemplate + Spring 4?

java - 适用于 Android 的 Google+ java 入门应用程序出现黑屏?

android - 我可以在 Google 上编辑登录按钮的文字吗?

google-plus - 如何在网站上显示我的 google+ 网站的帖子

安卓 Google+ 登录 "An internal error has occurred"

macos - 适用于 Mac 应用程序的 Instagram API