在挣扎了一些之后 SSL issues在我的机器上,我仍在尝试通过 Google Ruby Client API 访问用户的 Blogger 帐户。我正在使用以下内容:
我可以在验证时成功验证用户并通过 Google API 访问他们的博客。当用户登录时,我会存储
access_token
和 refresh_token
我从谷歌收到。一切正常,直到 access_token
到期。我正在尝试构建交换 refresh_token
的功能换新 access_token
,但不断撞墙。使用 client documentation例如,这是我正在使用的代码: client = Google::APIClient.new
token_pair = auth.oauth_token # access_token and refresh_token received during authentication
# Load the access token if it's available
if token_pair
client.authorization.update_token!(token_pair.to_hash)
end
# Update access token if expired
if client.authorization.refresh_token && client.authorization.expired?
client.authorization.fetch_access_token!
end
blogger = client.discovered_api('blogger', 'v3')
result = client.execute(
api_method: blogger.blogs.list_by_user,
parameters: {'userId' => "self", 'fields' => 'items(description,id,name,url)'},
headers: {'Content-Type' => 'application/json'})
此代码完美运行,而
access_token
已验证。但是,一旦它到期,我就会看到两个问题:expires_at
数据库中的值),client.authorization.expired?
返回 false
-- 除了使用数据库中的值之外,还有其他方法可以检查 token 的到期时间吗? client.authorization.fetch_access_token!
时我收到了 invalid_request
错误。 有人可以让我知道如何交换
refresh_token
换新 access_token
使用客户端 API?即使你知道如何用另一种语言来做,那也会有很大帮助,因为我可以尝试 Rubyfy。谢谢!!
最佳答案
你可能已经找到了这个,但你可以在谷歌这里阅读整个过程:https://developers.google.com/accounts/docs/OAuth2WebServer
omniauth-google-oauth2 策略已经负责设置访问类型和批准提示,因此获取刷新 token 只是发布到 https://accounts.google.com/o/oauth2/token 的问题。使用 grant_type=request_token
下面是我使用的大致代码:
def refresh_token
data = {
:client_id => GOOGLE_KEY,
:client_secret => GOOGLE_SECRET,
:refresh_token => REFRESH_TOKEN,
:grant_type => "refresh_token"
}
@response = ActiveSupport::JSON.decode(RestClient.post "https://accounts.google.com/o/oauth2/token", data)
if @response["access_token"].present?
# Save your token
else
# No Token
end
rescue RestClient::BadRequest => e
# Bad request
rescue
# Something else bad happened
end
关于ruby-on-rails - Rails Google Client API - 无法将刷新 token 交换为访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12572723/