【问题标题】:Google+ Authentication: refreshToken() returns invalid_grant errorGoogle+ 身份验证:refreshToken() 返回 invalid_grant 错误
【发布时间】:2014-10-07 15:17:30
【问题描述】:

我正在使用 Laravel 构建一个使用 Google 帐户作为登录方法的 Web 应用程序。我从 Github 下载了 Google+ PHP API,并编写了一个用于访问 Google+ 服务的单例类。该类的一个sn-p如下所示:

// 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

如果需要,我可以发布更多单例类,但考虑到我能够对用户进行身份验证并在第一个小时内发出请求,我认为这一切都是相关的。

类似但没有帮助的问题:

【问题讨论】:

    标签: php google-oauth google-api-php-client


    【解决方案1】:

    如果您希望使用刷新令牌刷新您的访问令牌,您可以这样做

    $client->refreshToken( $refresh_token );
    $_SESSION['token'] = $client->getAccessToken();
    

    如果您尝试刷新您最近授予的刷新令牌以外的其他内容,则会返回 invalid_grant。

    【讨论】:

      猜你喜欢
      • 2012-04-19
      • 2023-03-13
      • 2020-10-15
      • 2015-03-23
      • 2019-10-26
      • 2018-01-17
      • 1970-01-01
      • 2014-06-07
      • 2017-01-04
      相关资源
      最近更新 更多