为什么Google Drive API不断请求登录?



我正在使用Oauth与google drive ap合作。这是有效的,但是它每天都要求我的用户同意,并等待我登录我的谷歌帐户。

为什么我每天都要这么做?

是否按预期工作,我只是想确定我没有做错什么。

这是因为您的代码没有请求脱机访问,并且只有为凭据存储的访问令牌。

当你登录并同意你的应用程序访问你的数据时,认证服务器返回一个访问令牌。此访问令牌为您的应用程序提供一小时且仅一小时的访问权限。这就是为什么你必须每天请求访问。

你应该考虑的是请求离线访问并将刷新令牌存储在某个地方,这样你的应用程序就可以每天请求一个新的访问令牌,而不是再次提示用户。

oauthcallback.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();    
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

Oauth2Authentication.php

还有更多的代码,请查看git上的完整版本链接。

require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* @return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* @return A google client object.
*/
function buildClient(){

$client = new Google_Client();
$client->setAccessType("offline");        // offline access.  Will result in a refresh token
$client->setIncludeGrantedScopes(true);   // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());  
return $client;
}

最新更新