我见过很多关于Google-login-api刷新令牌的帖子,但无论我尝试什么方法都行不通,也不会给我一个新的令牌。
这是我的代码,当它没有获得刷新令牌时抛出异常。
OAuth 2.0访问令牌已过期,并且刷新令牌不可用。对于自动批准的响应,不会返回刷新令牌
// Check if the token is set to expire in the next 30 seconds
// (or has already expired).
if ($this->isAccessTokenExpired()) {
if ($this->assertionCredentials) {
$this->refreshTokenWithAssertion();
} else {
$this->client->getLogger()->debug('OAuth2 access token expired');
if (! array_key_exists('refresh_token', $this->token)) {
$error = "The OAuth 2.0 access token has expired,"
." and a refresh token is not available. Refresh tokens"
." are not returned for responses that were auto-approved.";
$this->client->getLogger()->error($error);
throw new Google_Auth_Exception($error);
}
$this->refreshToken($this->token['refresh_token']);
}
}
$this->client->getLogger()->debug('OAuth2 authentication');
// Add the OAuth2 header to the request
$request->setRequestHeaders(
array('Authorization' => 'Bearer ' . $this->token['access_token'])
);
return $request;
}
/**
* Fetches a fresh access token with the given refresh token.
* @param string $refreshToken
* @return void
*/
public function refreshToken($refreshToken)
{
$this->refreshTokenRequest(
array(
'client_id' => $this->client->getClassConfig($this, 'client_id'),
'client_secret' => $this->client->getClassConfig($this, 'client_secret'),
'refresh_token' => $refreshToken,
'grant_type' => 'refresh_token',
'approval_prompt' =>'force'
)
);
}
/**
* Fetches a fresh access token with a given assertion token.
* @param Google_Auth_AssertionCredentials $assertionCredentials optional.
* @return void
*/
public function refreshTokenWithAssertion($assertionCredentials = null)
{
if (!$assertionCredentials) {
$assertionCredentials = $this->assertionCredentials;
}
$cacheKey = $assertionCredentials->getCacheKey();
if ($cacheKey) {
// We can check whether we have a token available in the
// cache. If it is expired, we can retrieve a new one from
// the assertion.
$token = $this->client->getCache()->get($cacheKey);
if ($token) {
$this->setAccessToken($token);
}
if (!$this->isAccessTokenExpired()) {
return;
}
}
$this->client->getLogger()->debug('OAuth2 access token expired');
$this->refreshTokenRequest(
array(
'grant_type' => 'assertion',
'assertion_type' => $assertionCredentials->assertionType,
'assertion' => $assertionCredentials->generateAssertion(),
)
);
if ($cacheKey) {
// Attempt to cache the token.
$this->client->getCache()->set(
$cacheKey,
$this->getAccessToken()
);
}
}
如何获取api的刷新令牌?
文件: http://codepad.org/zo8wLJEE(完整Oauth2文件)