我正在使用Laravel构建一个Web应用程序,该应用程序使用Google帐户作为登录方法 . 我从Github下载了Google PHP API并编写了一个用于访问Google服务的单例类 . 这个类的片段如下所示:
// Returns a client ready to receive an access token.
private static function getClient() {
if (!self::$client) {
self::$client = new Google_Client();
self::$client->setApplicationName(self::$application_name);
self::$client->setClientId(self::$client_id);
self::$client->setClientSecret(self::$client_secret);
self::$client->setAccessType('offline');
// I'm only requesting the plus.login and userinfo.profile scopes.
self::$client->setScopes(self::$scopes);
// RedirectURI = 'postmessage'
self::$client->setRedirectUri(self::$redirect_uri);
}
return self::$client;
}
// Returns a client ready to be used for API calls.
private static function getClient2() {
$c = self::getClient();
// getToken returns the token session variable. This is the full
// JSON encoded token we got after authenticating the code.
$token = self::getToken();
$c->setAccessToken($token);
if ($c->isAccessTokenExpired()) {
// getRefreshToken returns the refresh_token session variable.
// This is a JSON decoded string that only contains
// the refresh_token value.
$refreshToken = self::getRefreshToken();
// This is the line that blows up.
$c->refreshToken($refreshToken);
// This code has never been reached :(
$newToken = $c->getAccessToken();
self::storeToken($newToken);
}
// If the access_token hasn't expired, we can merrily begin using
// the client to construct a Google_Service_Plus object.
return $c;
}
我正在实现混合客户端/服务器流程 . 用户第一次登录时,会调用JavaScript回调,该回调会发送要进行身份验证的代码 . 用户已通过身份验证, refresh_token
存储在数据库和当前会话中,我可以在 access_token
的生命周期内成功进行API调用 .
一小时后,访问令牌到期 . 我在 getClient2()
中对此进行了测试,并尝试使用从会话中检索到的 refresh_token
来刷新 access_token
(我已经打印了会话变量并且可以确认它们存在并且是json_decoded) . 然后我得到了精美的描述性错误
刷新OAuth2令牌时出错,消息:'invalid_grant'
此时,依赖于Google的所有页面都显示错误页面 . 除非用户返回到JavaScript再次开始登录流程的站点主页,否则该站点将无响应,从而允许服务器获得另一小时的有效 access_token
.
如果需要,我可以发布更多的单例类,但我认为这是相关的,因为我能够验证用户并在第一个小时发出请求 .
相似的问题,但没有帮助:
1 回答
如果您希望使用刷新令牌刷新访问令牌,则可以执行此操作
如果您尝试刷新最近授予的刷新令牌以外的其他内容,则会返回invalid_grant .