如何在 Ruby 中刷新 google 身份验证凭据

问题描述 投票:0回答:2

我能够完成身份验证流程来获取用户的凭据 - 但是,我想确保我可以继续使用这些凭据而不会过期。我完全了解令牌过期的规则。

但是,如果我想定期“刷新”用户的凭据,这样我就可以确保可以永久使用它们。我会这么做吗?

我看到 Google 的 documentation 说,“客户端对象将根据需要刷新访问令牌”....好吧,这是否意味着我只需要按如下方式初始化客户端对象,就像魔术一样,我的凭据将始终是是最新的吗?

    # one way...credentials is a hash with an access and refresh token and a bunch of other key value pairs

    Signet::OAuth2::Client.new(credentials)

    # another way
    client_secrets = Google::APIClient::ClientSecrets.new({web: credentials})

    auth_client = client_secrets.to_authorization

我很愿意相信该文档,但我可能会误读它。此外,如果我知道如何每月左右“刷新”用户的凭据以避免其过期的可能性,那就太好了。任何人都可以与我分享他们如何使用官方 google gem 定期刷新用户凭据,或者阐明有关此神奇刷新的文档,“客户端对象将根据需要刷新访问令牌”?

ruby oauth-2.0 google-oauth
2个回答
0
投票

是的,默认的 Ruby Google API 客户端 gem 确实包含自动刷新功能。正如您所提到的,您必须指定“离线”范围才能在第一次身份验证时首先获取刷新令牌。

也就是说,虽然我没有使用过 Signet,但我之前曾使用过 Omniauth 手动刷新令牌。事情是这样的。

def refresh_oauth
  strategy = OmniAuth::Strategies::GoogleOauth2.new(
    nil,
    Rails.application.secrets.fetch(:google_client_id),
    Rails.application.secrets.fetch(:google_client_secret),
  )

  client = strategy.client

  token = OAuth2::AccessToken.new(
    client,
    oauth_token,
    refresh_token: refresh_token,
  )

  token.refresh!
end

0
投票
require 'googleauth'
require 'googleauth/stores/file_token_store'

credentials_path = "path_to_file/client_secrets.json"
credentials = JSON.parse(File.read(credentials_path))['web']
data = {
  :client_id => credentials['client_id'],
  :client_secret => credentials['client_secret'],
  :refresh_token => credentials['refresh_token'],
  :project_id => credentials['project_id'],
  :scope => ['https://www.googleapis.com/auth/gmail.readonly']
}
authorizer = Google::Auth::UserRefreshCredentials.new(data)
new_access_token = authorizer.fetch_access_token['access_token']
puts new_access_token

参考:https://github.com/googleapis/google-auth-library-ruby/blob/main/lib/googleauth/user_refresh.rb

© www.soinside.com 2019 - 2024. All rights reserved.