curl - 使用 cURL 将文件上传到 Google Drive - access_token 过期问题
问题描述
我的目标是创建一个包含 cURL 请求的脚本,该脚本可以随时运行,无需任何手动输入即可将指定文件上传到我们的 Google Drive 帐户。
当我使用新创建的“access_token”时,我可以使用 cURL 将文件上传到 Google Drive。
但是,当我稍后运行相同的 cURL 命令来上传另一个文件时,我收到了无效凭据错误。
从阅读来看,这是由于“access_token”已过期。为了生成新的“access_token”,我需要生成一个新的“user_code”并在“https://www.google.com/device”上验证此代码。
由于我需要在没有任何手动输入的情况下运行脚本,因此我不想在每次需要上传文件时都生成“user_code”,因为这是手动步骤。
我是否应该在 cURL 请求中使用生成的“refresh_token”以便在任何给定时间上传文件?
任何帮助将不胜感激。
解决方案
为了访问 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
更新:
推荐阅读
- c# - 从 .net 应用程序执行 Oracle 存储过程
- sql - 从 SQL 构建 NodeJS 对象
- django - 为什么 Django views.py 在不更改 url 的情况下重定向到另一个视图?
- c - C - 从文件中选择随机字符串
- mysql - 如何并排显示单表查询的结果
- java - last==i 背后的直觉?
- feathersjs - 从服务调用自定义中间件
- java - SelectionTracker.Builder 不工作 IllegalArgumentException
- jquery - 如何在附加行中显示来自 validate() 的错误
- amazon-s3 - 无法使用 java dsl camel 组件连接到亚马逊 s3 客户端