在使用CURL通过REST API获取Azure Key Vaualt的Secrets值,提示Missing Token, 问如何来生成正确的Token呢?
# curl 命令 curl-k --request GET -H"Content-type: application/json;charset=UTF-8" -s https://<your key vault name>.vault.azure.cn/secrets/<secrets name >/<Secrets version number b38a011e4a82a8830b401af1a2384e72 # 错误消息 {"error":{"code":"Unauthorized","message":"AKV10000: Request is missing a Bearer or PoP token
通过-v 输出的更详细错误显示 401 Unauthorized,在curl发送的请求中缺少了 Authorization Header。而如果通过浏览器F12(开发者工具)获取到访问Key Vault Secret的Netwrok Trace获取的Authorization还是会遇见错误。
错误消息为:
{"error":{"code":"Unauthorized","message":"AKV10022: Invalid audience. Expected https://vault.azure.cn, found: https://management.core.chinacloudapi.cn/."}}
所以为了获取正确的Token:
进入 Azure ADApp registrations 页面(https://portal.azure.cn/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps),点击 “New registration”添加新的注册应用,输入名称后注册。
成功后,一定要记住一点。复制出 Application(Client) ID, Directory (tenant) ID,外加 在Certificates & Secrets页面中添加的Client Secrets. (将在第三步中使用)
同样,使用CURL命令调用AAD Token API,获取第四步的Authorization Token
在Windows中,POST请求的Body内容可以通过 --data “parameter1=value1¶meter2=value2”的格式传递。所以获取Token的CLUR命令为:
curl -k --request POST -H'Content-Type: application/x-www-form-urlencoded'
--data"grant_type=client_credentials&resource=https://vault.azure.cn&client_secret=your secret value&client_id=your aad client id"
-s https://login.chinacloudapi.cn/<your tenant id >/oauth2/token
从第三步中获取Token,放入获取Secrets的Header中。命令为:
curl -k --request GET -H"Content-type: application/json;charset=UTF-8"
-H"Authorization:Bearer <REPLACE CONTENT ey*********************>"
-s https://<your key vault name>.vault.azure.cn/secrets/<secrets name >/<Secrets version number b38a011e4a82a8830b401af1a2384e72?api-version=7.3
C:\>curl -h Usage: curl [options...]<url> -d, --data <data> HTTP POST data-f, --fail Fail silently (no output at all) on HTTP errors-h, --help <category> Get helpfor commands-i, --include Include protocol response headersin the output-o, --output <file> Write tofile instead of stdout-O, --remote-name Write output to afile named as the remotefile -s, --silent Silent mode-T, --upload-file <file> Transfer local FILE to destination-u, --user <user:password> Server user and password-A, --user-agent <name> Send User-Agent <name> to server-v, --verbose Make the operationmore talkative-V, --version Show version number and quit This is not the full help, this menu is stripped into categories. Use"--help category" to get an overview of all categories. For all options use the manual or"--help all".
Azure Key Vault REST API - Get Secret:https://docs.microsoft.com/zh-cn/rest/api/keyvault/secrets/get-secret/get-secret