我能够完成一个auth流来获取用户的凭据 - 但是,我想确保我可以继续使用这些凭据而不会使它们过期。我完全了解token expiration的规则。
但是,如果我想定期刷新'我有一个用户的凭据,所以我可以确保我可以永久使用它们。我会怎么做呢?
我看到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的用户凭据,或者对有关此神奇刷新的文档有所了解,"客户端对象将根据需要刷新访问令牌" ?
答案 0 :(得分:0)
是的,默认Ruby Google API client 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