use*_*714 5 oauth-2.0 google-plus
我已经阅读了有关如何使用Google API的文档,示例和教程,我已经运行了一个显示您最新活动和信息的迷你应用程序,但我使用会话来存储令牌.
我的问题是,如何从数据库中存储和检索令牌,以便当用户(已经注册)点击"登录"时,它可以立即使用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>
Run Code Online (Sandbox Code Playgroud)
非常感谢你的帮助!
问候,
约翰
如果您希望Google为已经授权您的应用程序的人员跳过授权提示,请在顶部的配置块中添加此代码:
$client->setAccessType("online");
$client-> setApprovalPrompt("auto");
Run Code Online (Sandbox Code Playgroud)
这个解决方案有一个好处:当你完成OAuth舞蹈时,你将不会收到刷新令牌.这意味着,每次访问令牌过期时,您的用户都会被重定向到Google的身份验证服务,以便获取新用户.这将大致每小时发生一次.
背景资料
默认情况下,PHP客户端库配置为提供脱机访问.您可以在源代码中看到这一点.启用此模式后,OAuth流将生成一个刷新令牌,可用于根据需要请求新的访问令牌.你可能甚至没有注意到这种情况.PHP客户端库会为您处理大部分内容.
但是,这个刷新令牌需要付出代价.您负责存储它.如果您丢失了它,您的用户必须重新授权您的应用程序,以便您再次发布.您存储它的方式很大程度上取决于您的实现细节.会话数据是一种合理的方法,如果你可以使它足够持久.
| 归档时间: |
|
| 查看次数: |
5289 次 |
| 最近记录: |