使用 Google Calendar API Ruby 库时如何获取刷新令牌?

问题描述 投票:0回答:1

我是一名新手,试图将 Google Calendar API 实现到基于网络的应用程序中,在按照他们提供给 t 的说明进行操作后,获取信息只能持续大约 20 分钟(而访问令牌仍然有效)。我知道您需要刷新令牌才能生成新的访问令牌,但从终端运行此脚本(谷歌在其文档中提供)不会提供刷新令牌。

我在终端中执行的代码:

google-api oauth-2-login --scope=https://www.googleapis.com/auth/calendar --client-                id=CLIENT_ID --client-secret=CLIENT_SECRET

这生成了一个包含我所有密钥的 .yaml 文件,如下所示:

---
mechanism: oauth_2
scope: SCOPE_HERE
client_id: CLIENT_ID_HERE
client_secret: CLIENT_SECRET_HERE
access_token: ACCESS_TOKEN_HERE
refresh_token: 

如果访问令牌过期,他们提供的代码:

oauth_yaml = YAML.load_file('.google-api.yaml')
client = Google::APIClient.new
client.authorization.client_id = oauth_yaml["client_id"]
client.authorization.client_secret = oauth_yaml["client_secret"]
client.authorization.scope = oauth_yaml["scope"]
client.authorization.refresh_token = oauth_yaml["refresh_token"]
client.authorization.access_token = oauth_yaml["access_token"]

if client.authorization.refresh_token && client.authorization.expired?
  client.authorization.fetch_access_token!
end

service = client.discovered_api('calendar', 'v3')

因此,根据 yaml 文件,client.authorization.refresh_token 始终为“nil”,并且它永远不会获得新的访问令牌。另外,client.authorization.expired?始终返回 false,即使应用程序停止工作后也是如此。 我在这里看到了与同一问题有关的其他一些问题,但由于我是通过终端命令生成令牌的,所以我不太确定如何获取刷新令牌。

ruby google-calendar-api
1个回答
0
投票

您需要指定您想要离线访问以获得刷新令牌:access_type=offline

请参阅 https://developers.google.com/accounts/docs/OAuth2WebServer#offline

© www.soinside.com 2019 - 2024. All rights reserved.