如何使用刷新令牌刷新google_oauth2访问令牌?

我有一个RoR应用程序,我使用omniauth和google_oauth2对Google进行身份validation,我要求离线访问。

如何使用刷新令牌请求当前访问令牌? 此外,如果访问令牌不再有效,我该如何刷新它? 我不希望在这种情况下有任何用户界面,当然假设授权尚未被删除。

我在google_oauth2中没有看到任何处理带有刷新令牌的新access_token ,所以看起来你需要直接进行交换。

Google的官方OAuth 2.0文档解释了如何在较低级别执行此操作。 在服务器端代码中,使用您喜欢的HTTP客户端构建如下所示的请求:

 POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded client_id=CLIENT_ID& client_secret=CLIENT_SECRET& refresh_token=REFRESH_TOKEN& grant_type=refresh_token 

其中CLIENT_IDCLIENT_SECRET与原始身份validation使用的相同, REFRESH_TOKEN是原始身份validation流程中的刷新令牌。 如果交换成功,您将在响应中收到一个新的访问令牌,如下所示:

 { "access_token":"1/fFBGRNJru1FQd44AzqT3Zg", "expires_in":3920, "token_type":"Bearer", } 

您可以按照此过程在需要时随时获取新的访问令牌。 您可以使用expires_in值来估计何时需要新值,或者在API请求以401 HTTP状态响应时尝试刷新。

有关使用Ruby HTTParty gem的示例:

其中@auth是一个ActiveRecord记录,用于存储您尝试刷新令牌的特定用户的身份validation密钥。

  # Refresh auth token from google_oauth2 and then requeue the job. options = { body: { client_id: , client_secret: , refresh_token: @auth.refresh_token, grant_type: 'refresh_token' }, headers: { 'Content-Type' => 'application/x-www-form-urlencoded' } } @response = HTTParty.post('https://accounts.google.com/o/oauth2/token', options) if @response.code == 200 @auth.token = @response.parsed_response['access_token'] @auth.expires_in = DateTime.now + @response.parsed_response['expires_in'].seconds @auth.save else Rails.logger.error("Unable to refresh google_oauth2 authentication token.") Rails.logger.error("Refresh token response body: #{@response.body}") end