【问题标题】:get google Oauth2 access token using ONLY curl仅使用 curl 获取 google Oauth2 访问令牌
【发布时间】:2021-04-04 10:06:48
【问题描述】:

我想使用 curl 将 pdf 文件上传到 Google Drive,用于自动化测试。

我在 Google Cloud Platform 上创建了一个帐户(获取了客户端 ID 和 Secret)并启用了 Google Drive API。

使用 OAuth2 进行连接的所有方法都涉及网络浏览器或单击某些按钮,我不打算这样做。

有没有办法让使用 OAuth2 进行身份验证并获取访问令牌以能够使用它上传文件的整个过程,在 cmd 终端中使用 ONLY curl 命令?

谢谢。

【问题讨论】:

    标签: curl google-cloud-platform oauth-2.0 google-api google-oauth


    【解决方案1】:

    以下命令将向您展示如何使用 Curl 向 Google 授权。拥有刷新令牌后,您将必须至少使用一次网络浏览器才能获得刷新令牌,之后您可以使用该命令再次请求一个新令牌。

    # 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=[Authentication 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
    

    提示:

    上传分为两部分,您需要上传元数据,然后是实际文件的文件流。

    创建和更新是有区别的。如果它是一个现有文件,您将需要使用更新而不是创建,否则您每次都会获取一个新文件。

    GoogleAuthenticationCurl.sh 窃取的代码

    服务帐号

    如果您想要完全解放双手,那么您应该查看一个服务帐户,我无法在 curl 中帮助您这样做,由于所有安全性和令牌的生成,我什至不确定它是否可能。

    刷新令牌过期

    refresh tokens 的官方文档及其可能的到期日期

    • 用户已撤消您应用的访问权限。
    • 刷新令牌已有六个月未使用。
    • 用户更改了密码,并且刷新令牌包含 Gmail 范围。
    • 用户帐户已超过授予(实时)刷新令牌的最大数量。 (目前每个 OAuth 2.0 客户端 ID 的每个 Google 帐户的刷新令牌限制为 50 个。如果达到限制,创建新的刷新令牌会自动使最旧的刷新令牌失效,而不会发出警告。)

    【讨论】:

    • 首先,感谢您的快速回复@DaImTo。关于刷新令牌,它会在一定时间后过期吗?
    • 只要您每六个月至少使用一次刷新令牌,它就不会过期
    • 更新。处于测试阶段的应用的刷新令牌将在 7 天后过期
    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 2019-08-17
    • 2021-10-10
    • 2015-02-11
    • 2014-11-06
    • 2019-04-05
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多