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

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

问题描述

我有一个 RoR 应用,我使用 omniauth 和 google_oauth2 对 Google 进行身份验证,我请求离线访问.

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.

推荐答案

我在 google_oauth2 中没有看到任何处理使用刷新令牌获取新 access_token 的内容,所以看起来你需要直接进行交换.

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 的官方 OAuth 2.0 文档 解释了如何在较低级别执行此操作.在您的服务器端代码中,使用您最喜欢的 HTTP 客户端构建一个如下所示的请求:

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

其中 CLIENT_IDCLIENT_SECRET 与您用于原始身份验证的相同,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",
}

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

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天全站免登陆