如何使用我的刷新令牌刷新我的google_oauth2访问令牌? [英] How do I refresh my google_oauth2 access token using my refresh token?

查看:266
本文介绍了如何使用我的刷新令牌刷新我的google_oauth2访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RoR应用程序,我正在使用omniauth和google_oauth2进行身份验证,请求脱机访问。



如何使用我的刷新令牌请求当前访问令牌?另外,如何在不再有效时刷新我的访问令牌?我不希望在这种情况下有任何用户界面,当然假设授权没有被拿走。

解决方案

p>我没有看到 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

其中 CLIENT_ID CLIENT_SECRET 与您用于原始认证的相同,而 REFRESH_TOKEN 是来自原始认证流程的刷新令牌。如果交易成功,您会在响应中收到一个新的访问令牌,如下所示:

  {
access_token:1 / fFBGRNJru1FQd44AzqT3Zg,
expires_in:3920,
token_type:承载者,
}

您可以按照此过程在需要时获取新的访问令牌。您可以使用 expires_in 值来估计什么时候需要一个新的API,或者当您的API请求响应401 HTTP状态时尝试刷新。


I have a RoR app where I am authenticating against Google using omniauth and google_oauth2 where I am requesting offline access.

How do I use my refresh token to request a current access token? Also, how can I refresh my access token when it no longer works? I don't want to have any user interface in this situation, assuming of course that the authorization hasn't been taken away.

解决方案

I don't see anything in google_oauth2 that handles fetching a new access_token with a refresh token, so it looks like you'll need to make the exchange directly.

Google's official OAuth 2.0 documentation explains how to do this at a low level. Within your server-side code, use your favorite HTTP client to construct a request that looks like this:

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

where CLIENT_ID and CLIENT_SECRET are the same ones you used for the original authentication and REFRESH_TOKEN is the refresh token from the original authentication flow. If the exchange is successful, you'll receive a fresh access token in a response that looks something like this:

{
  "access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
}

You can follow this process to grab a new access token whenever you need one. You can either use the expires_in value to estimate when you will need a new one, or attempt a refresh whenever your API request responds with a 401 HTTP status.

这篇关于如何使用我的刷新令牌刷新我的google_oauth2访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆