hud*_*onn 7 php google-login oauth-2.0
我正在尝试使用google oauth2 api登录系统.它几乎正常工作,用户可以访问我的Web应用程序,读取信息并连接用户.问题是,一旦他们离开或更改浏览器,回到我的网站,他们再次被要求提供访问权限.
我不需要离线访问,因为除了检查用户之外我没有使用任何API调用.无论如何,我被困住了,需要一些帮助!
我正在使用谷歌php库(https://code.google.com/p/google-api-php-client/wiki/OAuth2),我甚至将ApprovalPrompt设置为auto.仍然没有运气.
我的代码:
public function googleLogin()
{
$this->set('connect', "Google login");
$client = new apiClient();
$client->setApprovalPrompt('auto');
$client->setApplicationName("Authentication");
$client->setClientId(G_OAUTH2_APP_ID);
$client->setClientSecret(G_OAUTH2_SECRET);
$client->setRedirectUri(G_REDIRECT_URI);
$client->setDeveloperKey(G_DEV_KEY);
$oauth2 = new apiOauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
//print_r($client->getAccessToken()); exit;
if ($client->getAccessToken()) {
$user = $oauth2->Guserinfo->get();
// These fields are currently filtered through the PHP sanitize filters.
// See http://www.php.net/manual/en/filter.filters.sanitize.php
//$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
//$img = filter_var($user['picture'], FILTER_VALIDATE_URL);
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
//do stuff with user data
$data = $this->linkUser($user, "google");
if ($data['state']=="createUser") {
$this->set("data",$data);
}
} else {
$authUrl = $client->createAuthUrl();
header("Location: " . $authUrl);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我添加了$client->setAccessType("online");
我不知道的行,如果这是我必须做的唯一的事情,使它工作或我有一个浏览器/操作系统之间的错误:上次我尝试狮子/铬它不起作用但它在w7/firefox上没问题.好吧,或者我只是在放松自己的想法:p
您必须将用户第一次授予对您的应用程序的访问权限时获得的刷新令牌保存在数据库中,并在将来的请求中重复使用它。
Google Drive SDK 文档包含一个实现该流程的示例 PHP 应用程序,您可以将其用作参考:
https://developers.google.com/drive/examples/php