【问题标题】:Uploading files to Google Drive using cURL - access_token expiry issue使用 cURL 将文件上传到 Google Drive - access_token 过期问题
【发布时间】:2021-03-01 07:26:09
【问题描述】:

我的目标是创建一个包含 cURL 请求的脚本,该脚本可以随时运行,无需任何手动输入即可将指定文件上传到我们的 Google Drive 帐户。

当我使用新创建的“access_token”时,我可以使用 cURL 将文件上传到 Google 云端硬盘。

但是,当我稍后运行相同的 cURL 命令上传另一个文件时,我收到了无效凭据错误。

从阅读来看,这是由于“access_token”已过期。为了生成新的“access_token”,我需要生成一个新的“user_code”并在“https://www.google.com/device”验证此代码。

由于我需要在没有任何手动输入的情况下运行脚本,因此我不想在每次需要上传文件时都生成“user_code”,因为这是手动步骤。

我是否应该在 cURL 请求中使用生成的“refresh_token”以便在任何给定时间上传文件?

任何帮助将不胜感激。

【问题讨论】:

  • 例如,在 Drive API Quickstart 的示例脚本中,API 与刷新令牌检索到的访问令牌一起使用。这样,就不需要每次都用浏览器检索授权码。我认为服务帐户也可以使用。但在这种情况下,需要实现使用服务帐户检索访问令牌的脚本。从这种情况来看,如果您已经拥有刷新令牌或者可以检索它,我建议您使用刷新令牌。如果这不是您期望的方向,我很抱歉。
  • 我可以毫无问题地使用 cURL 进行连接。令牌过期更是一个问题。感谢您的回复。

标签: curl oauth google-api google-drive-api google-oauth


【解决方案1】:

为了访问 google api,您需要有一个访问令牌。如您所知,访问令牌会在一小时后过期,那么您需要请求新的访问令牌。当您第一次授权用户时,明智的做法是也请求离线访问。这将返回给您一个刷新令牌。然后,当您的代码运行时,我建议使用刷新令牌来请求新的访问令牌,那么您将始终使用一个可以使用一个小时的访问令牌运行。

以下内容摘自我的一个要点Googleauthnecation.sh

请求访问权限。

记得为你的作用域添加“离线”访问权限。

# Client id from Google Developer console
# Client Secret from Google Developer console
# Scope this is a space separated list of the scopes of access you are requesting.

# Authorization link.  Place this in a browser and copy the code that is returned after you accept the scopes.
https://accounts.google.com/o/oauth2/auth?client_id=[Application Client Id]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=[Scopes]&response_type=code

# Exchange Authorization code for an access token and a refresh token.

curl \
--request POST \
--data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token

用刷新令牌交换新的访问令牌。

# Exchange a refresh token for a new access token.
curl \
--request POST \
--data 'client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token' \
https://accounts.google.com/o/oauth2/token

更新:

另见How to connect to the Google Drive API using cURL?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2020-03-10
    • 2015-09-13
    相关资源
    最近更新 更多