【问题标题】:How do I refresh my google_oauth2 access token using my refresh token?如何使用我的刷新令牌刷新我的 google_oauth2 访问令牌?
【发布时间】:2012-09-29 07:54:30
【问题描述】:

我有一个 RoR 应用程序,我在其中使用 omniauth 和 google_oauth2 对 Google 进行身份验证,我请求离线访问。

如何使用我的刷新令牌来请求当前的访问令牌?另外,当我的访问令牌不再有效时,如何刷新它?在这种情况下,我不想有任何用户界面,当然前提是授权没有被取消。

【问题讨论】:

    标签: ruby-on-rails google-api oauth-2.0 omniauth


    【解决方案1】:

    以使用 Ruby HTTParty gem 为例:

    @auth 是一条 ActiveRecord 记录,它存储您尝试为其刷新令牌的特定用户的身份验证密钥。

      # Refresh auth token from google_oauth2 and then requeue the job.
      options = {
        body: {
          client_id: <YOUR GOOGLE API CLIENT ID HERE>,
          client_secret: <YOUR GOOGLE API SECRET KEY HERE>,
          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
    

    【讨论】:

    • 你会在你的 Rails 应用程序中的什么地方实现它?例如,我有一个获取请求以使用发送令牌的 httparty 检索用户联系人,如果令牌已过期,我怎么说发布刷新令牌?
    • 我上面发布的代码是执行 POST 请求以刷新令牌的代码。执行 GET 请求后,我会检查响应代码是否等于 401,这通常是您需要刷新令牌时获得的代码。如果 HTTParty 响应代码 == 401 然后运行我的代码(根据您的需要进行调整)。
    【解决方案2】:

    我在google_oauth2 中看不到任何处理使用刷新令牌获取新access_token 的内容,因此您似乎需要直接进行交换。

    Google's official OAuth 2.0 documentation 解释了如何在低级别执行此操作。在您的服务器端代码中,使用您最喜欢的 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 与您用于原始身份验证的相同,REFRESH_TOKEN 是来自原始身份验证流程的刷新令牌。如果交换成功,您将在响应中收到一个新的访问令牌,如下所示:

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

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

    【讨论】:

      猜你喜欢
      • 2022-10-31
      • 2020-07-12
      • 2014-01-11
      • 2019-06-29
      • 2017-01-18
      • 2014-09-13
      • 2016-09-23
      • 2016-03-13
      • 1970-01-01
      相关资源
      最近更新 更多