使用 cURL 将文件上传到 Google 驱动器 - access_token 过期问题

Uploading files to Google Drive using cURL - access_token expiry issue

我的目标是拥有一个带有 cURL 请求的脚本,可以随时 运行 将指定的文件上传到我们的 Google 云端硬盘帐户,而无需任何手动输入。

当我使用新创建的“access_token”时,我可以使用 cURL 将文件上传到 Google 驱动器。

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

据了解,这是因为“access_token”过期了。为了生成一个新的“access_token”,我需要生成一个新的“user_code”并在“https://www.google.com/device”验证此代码.

因为我要求脚本是 运行 而无需任何手动输入,所以我不想每次需要上传文件时都必须生成“user_code”,因为这是手动步骤。

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

如有任何帮助,我们将不胜感激。

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

以下内容摘自我的一个要点 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?