如何使用Curl CLI执行OAuth 2.0?
此答案适用于Windows命令提示符用户,但也应易于适应Linux和Mac。
你需要你的谷歌
Client ID
Client Secret
. 可以从谷歌控制台的
APIs & Services
-&燃气轮机;
Credentials
.
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批处理文件中。
-
修改以适应您的环境。
-
修改要使用的浏览器的脚本。
-
运行批处理文件。
-
-
浏览器将转到
https://accounts.google.com
您可以在其中完成Google OAuth 2.0身份验证。
-
-
从浏览器窗口复制此代码(control-c)并粘贴到命令提示窗口(control右键单击)。
-
该脚本将完成令牌的OAuth 2.0代码交换。
-
该令牌将显示在命令提示符中。
-
返回的令牌包含一个访问令牌,可以在更多curl命令中使用。
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、保存和刷新令牌,然后模拟服务帐户。
PowerShell â Impersonate Google Service Account