【发布时间】:2020-03-21 04:44:34
【问题描述】:
我想在 Windows 命令提示符下使用 curl 来执行 Google OAuth 2.0。我的目标是更好地理解 OAuth 服务器实现的身份验证流程,查看 HTTP 标头等。
如何使用来自 Windows 命令提示符的 curl.exe 来完成此操作?
【问题讨论】:
标签: curl oauth-2.0 google-cloud-platform google-oauth
我想在 Windows 命令提示符下使用 curl 来执行 Google OAuth 2.0。我的目标是更好地理解 OAuth 服务器实现的身份验证流程,查看 HTTP 标头等。
如何使用来自 Windows 命令提示符的 curl.exe 来完成此操作?
【问题讨论】:
标签: curl oauth-2.0 google-cloud-platform google-oauth
如何使用 Curl CLI 执行 OAuth 2.0?
此答案适用于 Windows 命令提示符用户,但也应该很容易适应 Linux 和 Mac。
您将需要您的 Google Client ID 和 Client Secret。这些可以从APIs & Services -> Credentials 下的 Google 控制台获得。
在以下示例中,范围为cloud-platform。修改以使用您要测试的范围。您可以使用以下几个范围进行测试:
"https://www.googleapis.com/auth/cloud-platform"
"https://www.googleapis.com/auth/cloud-platform.read-only"
"https://www.googleapis.com/auth/devstorage.full_control"
"https://www.googleapis.com/auth/devstorage.read_write"
"https://www.googleapis.com/auth/devstorage.read_only"
"https://www.googleapis.com/auth/bigquery"
"https://www.googleapis.com/auth/datastore"
OAuth 2.0 Scopes for Google APIs
详情:
Windows 批处理脚本:
set CLIENT_ID=Replace_with_your_Client_ID
set CLIENT_SECRET=Replace_with_your_Client_Secret
set SCOPE=https://www.googleapis.com/auth/cloud-platform
set ENDPOINT=https://accounts.google.com/o/oauth2/v2/auth
set URL="%ENDPOINT%?client_id=%CLIENT_ID%&response_type=code&scope=%SCOPE%&access_type=offline&redirect_uri=urn:ietf:wg:oauth:2.0:oob"
@REM start iexplore %URL%
@REM start microsoft-edge:%URL%
start chrome %URL%
set /p AUTH_CODE="Enter Code displayed in browser: "
curl ^
--data client_id=%CLIENT_ID% ^
--data client_secret=%CLIENT_SECRET% ^
--data code=%AUTH_CODE% ^
--data redirect_uri=urn:ietf:wg:oauth:2.0:oob ^
--data grant_type=authorization_code ^
https://www.googleapis.com/oauth2/v4/token
最终输出如下:
{
"access_token": "ya29.deleted_for_security_reasons",
"expires_in": 3600,
"refresh_token": "1/jk3/deleted_for_security_reasons",
"scope": "https://www.googleapis.com/auth/cloud-platform",
"token_type": "Bearer"
}
使用访问令牌的 curl 命令示例:
set ACCESS_TOKEN=replace_with_your_access_token
set PROJECT=development-123456
set ZONE=us-west-1a
set INSTANCE_NAME=dev-system
@REM - This endpoint will start the instance named INSTANCE_NAME in ZONE
set ENDPOINT=https://www.googleapis.com/compute/v1/projects/%PROJECT%/zones/%ZONE%/instances/%INSTANCE_NAM%/start
curl -H "Authorization: Bearer %ACCESS_TOKEN" "%ENDPOINT%"
提示:将访问令牌保存到文件中
修改批处理脚本的最后一行,使用jq处理输出:
curl ^
--data client_id=%CLIENT_ID% ^
--data client_secret=%CLIENT_SECRET% ^
--data code=%AUTH_CODE% ^
--data redirect_uri=urn:ietf:wg:oauth:2.0:oob ^
--data grant_type=authorization_code ^
https://www.googleapis.com/oauth2/v4/token | jq -r ".access_token > token.save
set /p ACCESS_TOKEN=<token.save
echo %ACCESS_TOKEN%
最后两行展示了如何读取保存到文件中的访问令牌,以便在更多脚本中进一步使用。
记住,令牌在 60 分钟后过期,这是默认值。
我在我的博客上写了一篇文章详细说明了这一点:
Google OAuth 2.0 – Testing with Curl
[2020 年 3 月 18 日更新]
我写了一篇关于如何在 Powershell 中执行 OAuth 的文章。本文介绍如何进行 OAuth、保存和刷新令牌,然后模拟服务帐户。
【讨论】: