如何获取新的刷新 Google OAuth 令牌

How to get new refresh Google OAuth token

我有一些代码(服务器上的脚本)尝试发送 OAuth2 请求以从 API 获取令牌。我在 Google 云平台 > API 和服务中的“凭据”选项卡的“OAuth 2.0 客户端 ID”部分有一个客户端 ID 和客户端密码。我还有一个我最初以某种方式获得的刷新令牌。

我要发帖的 URL 是:

https://www.googleapis.com/oauth2/v4/token

我正在发送 header

Content-Type: application/x-www-form-urlencoded

在我的 post 的 body 中,我有以下信息:

grant_type=refresh_token&client_id=${encodeURIComponent(client_id)}&client_secret=${encodeURIComponent(client_secret)}&refresh_token=${encodeURIComponent(refresh_token)}                                                                             

然而,自从我上次 运行 这段代码以来已经有很长一段时间了,现在它 returns 一个错误“bad g运行t”。在 this page 上,它表示如果六个月未使用刷新令牌,它将停止工作,这解释了为什么我会收到错误消息。但是,它没有说明如何使用客户端 ID 和客户端密码获取另一个刷新令牌,类似于我现在创建 post 以获取访问令牌的方式。我该怎么做?

我认为您的目标和现状如下。

  • 您想从当前的客户端 ID 和客户端密码中检索新的刷新令牌。
  • 您的客户端 ID 和客户端密码是有效值。

在这种情况下,为了检索新的刷新令牌,需要使用 scoperedirect_uri 的附加 2 个参数。这些参数可以在 Google 云平台中“凭据”选项卡的“OAuth 2.0 客户端 ID”中创建的客户端 ID 中确认。当使用client_idclient_secretscoperedirect_uri参数时,可以获取新的refresh token。流程如下。

1。检索授权码。

请使用 client_idredirect_uriscope 创建以下端点。

https://accounts.google.com/o/oauth2/auth?client_id={your client ID}&redirect_uri={your redirect uri}&scope={your scopes}&response_type=code&approval_prompt=force&access_type=offline

当您创建以上端点时,请访问您的浏览器。由此,登录画面被打开。当您登录到 Google 帐户时,授权屏幕将打开。当您允许范围时,可以检索授权代码。

当您的凭据用于网络应用程序时,您可以在浏览器上的 URL 检索代码,如 http://{your redirect uri}/?code={the authorization code}&scope={your scopes}

请复制代码。

2。检索刷新令牌。

使用检索到的授权码,您可以检索新的刷新令牌。示例 curl 命令如下。

curl \
  -d "client_id={your client ID}" \
  -d "client_secret={your client secret}" \
  -d "redirect_uri={your redirect uri}" \
  -d "grant_type=authorization_code" \
  -d "code={retrieved your authorization code}" \
  "https://www.googleapis.com/oauth2/v4/token"

当上述curl命令为运行时,得到如下结果

{
  "access_token": "###",
  "expires_in": 3600,
  "refresh_token": "###",
  "scope": "{your scopes}",
  "token_type": "Bearer"
}

参考: