如何使用Ruby客户端刷新Google API的access_token?

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

我有一个正在运行的应用程序(Rails),它可以对用户进行身份验证并将其令牌保存在 Redis 存储中。

如果我理解正确,将 googleauth 与 google-api-client 一起使用,客户端对象将根据需要刷新访问令牌(自行)?但这并没有发生,令牌过期,一段时间后我收到 403 错误。

如果问题出在我这边 - 我可以/应该手动调用新的 access_token 吗?如果可以,我该怎么做?

我使用的代码主要取自快速入门指南

gem 'google-api-client', require: 'google/apis/calendar_v3'

def authorizer
  scope = Google::Apis::CalendarV3::AUTH_CALENDAR
  client_id = Google::Auth::ClientId.from_hash(JSON.parse(ENV['GOOGLE_CLIENT_SECRETS']))
  token_store = Google::Auth::Stores::RedisTokenStore.new(redis: $redis)
  authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope, token_store)
  authorizer
end

def authenticate_the_user
  user_id = "1"
  credentials = authorizer.get_credentials(user_id)
  redirect_to authorizer.get_authorization_url(login_hint: user_id, request: request, base_url: "http://localhost:3000")
end

def handle_callback
  credentials = authorizer.get_and_store_credentials_from_code(user_id: "1", code: params[:code], base_url: "http://localhost:3000/oauth2callback")
end
ruby google-api google-api-client google-authentication google-api-ruby-client
1个回答
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.