【发布时间】:2012-09-29 07:54:30
【问题描述】:
我有一个 RoR 应用程序,我在其中使用 omniauth 和 google_oauth2 对 Google 进行身份验证,我请求离线访问。
如何使用我的刷新令牌来请求当前的访问令牌?另外,当我的访问令牌不再有效时,如何刷新它?在这种情况下,我不想有任何用户界面,当然前提是授权没有被取消。
【问题讨论】:
标签: ruby-on-rails google-api oauth-2.0 omniauth
我有一个 RoR 应用程序,我在其中使用 omniauth 和 google_oauth2 对 Google 进行身份验证,我请求离线访问。
如何使用我的刷新令牌来请求当前的访问令牌?另外,当我的访问令牌不再有效时,如何刷新它?在这种情况下,我不想有任何用户界面,当然前提是授权没有被取消。
【问题讨论】:
标签: ruby-on-rails google-api oauth-2.0 omniauth
以使用 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
【讨论】:
我在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_ID 和CLIENT_SECRET 与您用于原始身份验证的相同,REFRESH_TOKEN 是来自原始身份验证流程的刷新令牌。如果交换成功,您将在响应中收到一个新的访问令牌,如下所示:
{
"access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
"expires_in":3920,
"token_type":"Bearer",
}
您可以在需要时按照此流程获取新的访问令牌。您可以使用 expires_in 值来估计何时需要新的,或者在您的 API 请求以 401 HTTP 状态响应时尝试刷新。
【讨论】: