Eri*_*ric 8 ruby-on-rails google-api oauth-2.0 omniauth
我有一个RoR应用程序,我使用omniauth和google_oauth2对Google进行身份验证,我要求离线访问.
如何使用刷新令牌请求当前访问令牌?此外,如果访问令牌不再有效,我该如何刷新它?我不希望在这种情况下有任何用户界面,当然假设授权尚未被删除.
有关使用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
Run Code Online (Sandbox Code Playgroud)
我没有看到google_oauth2该句柄中有任何内容access_token使用刷新令牌获取新内容,因此看起来您需要直接进行交换.
Google的官方OAuth 2.0文档解释了如何在较低级别执行此操作.在服务器端代码中,使用您喜欢的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
Run Code Online (Sandbox Code Playgroud)
在那里CLIENT_ID和CLIENT_SECRET你使用的原始身份验证相同的人,并REFRESH_TOKEN从原来的认证流程的刷新令牌.如果交换成功,您将在响应中收到一个新的访问令牌,如下所示:
{
"access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
"expires_in":3920,
"token_type":"Bearer",
}
Run Code Online (Sandbox Code Playgroud)
您可以按照此过程在需要时随时获取新的访问令牌.您可以使用该expires_in值来估计何时需要新值,或者在API请求以401 HTTP状态响应时尝试刷新.