【Azure 环境】用 PowerShell 调用 AAD Token, 以及调用Azure REST API(如资源组列表)

简介: 【Azure 环境】用 PowerShell 调用 AAD Token, 以及调用Azure REST API(如资源组列表)

问题描述

PowerShell 脚本调用Azure REST API, 但是所有的API都需要进行权限验证。要在请求的Header部分带上Authorization参数,并用来对List Resource Group接口进行授权,然后显示Resource Group的Name,Location,和ID ...

问题解答

第一步:在Azure AD中注册应用,该应用表示执行PowerShell Script的客户端拥有访问Subscription下资源的权限。如无,则会出现 AuthorizationFailed 错误,详见附录一:权限问题

  1. 在浏览器上的新标签页中打开 Azure 门户。
  2. 导航到“应用注册”以在 Active Directory 中注册应用。
  3. 选择“新注册”。 在“注册应用程序”页上,将值设置如下:
  • 将“名称”设置为一个有意义的名称。 例如,powershell-client
  • 将“支持的帐户类型”设置为“仅限此组织目录中的帐户”。
  • 选择“注册” 。
  1. 注册应用程序之后,从“概述”页复制“应用程序(客户端) ID” 和 “ 目录(tenant) ID ”。
  2. 在边侧菜单的“管理”部分下,选择“证书和机密” 。
  3. 在“证书和机密”页中,选择“客户端机密”下的“新建客户端机密”按钮 。
  • 输入“说明”。
  • 为“过期”选择任一选项。
  • 选择“添加” 。
  1. 在离开页面之前复制客户端的“机密 ID”。 稍后脚本中需要用到此值。

 

第二步:在下面脚本中替换自己的 tenantIdapplicationId secret

#===============================================
# 2021-11-14 通过Azure AD中的注册应用获取Access Token
# 
# Azure AD App Registrations: https://portal.azure.cn/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps
# 【Azure Developer】使用Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorization: https://www.cnblogs.com/lulight/p/14279338.html
#===============================================
$tenantId='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$applicationId='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$secret='-xxxx~xxxxxxxxxxxxxxxxxxxxxxxx'
$param = @{
    Uri ="https://login.chinacloudapi.cn/$tenantId/oauth2/token";
    Method = 'Post';
    Body = @{
        grant_type = 'client_credentials';
        resource = 'https://management.chinacloudapi.cn';
        client_id = $applicationId;
        client_secret = $secret
    }
}
Write-Host '调用Token接口 .. ' -ForegroundColor DarkYellow
$result = Invoke-RestMethod @param
$result
#===============================================
#
# 使用Token作为Authorization,调用Resource Groups - List: https://docs.microsoft.com/en-us/rest/api/resources/resource-groups/list
#
#===============================================
$subscriptionId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$token = $result.access_token
$param_rgList = @{
    Uri = "https://management.chinacloudapi.cn/subscriptions/$subscriptionId/resourcegroups?api-version=2020-06-01";
    ContentType = 'application/json';
    Method = 'GET'
    Headers = @{
        Authorization = "Bearer $token";
        host = "management.chinacloudapi.cn"
    }
}
Write-Host '调用 Resource Groups - List 接口 .. ' -ForegroundColor DarkYellow
$rgList =  Invoke-RestMethod @param_rgList
$rgList.value | Select-Object name, location, id

执行结果:

 

 

附录一:权限问题

错误消息:

Invoke-RestMethod : {"error":{"code":"AuthorizationFailed","message":"The client '0b807bf1-40db-4e0c-888f-380b9b558cf1' with object id '0b807bf1-40db-4e0c-888f-380b9b558cf1' does not have authorization 
to perform action 'Microsoft.Resources/subscriptions/resourcegroups/read' over scope '/subscriptions/a9dc7515-7692-4316-9ad4-762f383eec10' or the scope is invalid. If access was recently granted, 
please refresh your credentials."}}
At line:49 char:12
+ $rgList =  Invoke-RestMethod @param_rgList
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

错误截图:

解决办法:

在门户中进入Subscriptions页面,对注册应用赋予Reader权限即可。

1) 进入Azure Subscriptions页面:https://portal.azure.cn/#blade/Microsoft_Azure_Billing/SubscriptionsBlade

2) 选中订阅,在Access Control(IAM)中对第一步中 AAD的注册应用赋予Reader权限。  

 

 

附录二:PowerShell中URL后携带参数的‘?’需要转义

因为PowerShell的变量名中后不能为符号,如 ? 等,需要添加 ` 作为转义字符(高亮部分),改为 '?。

如:

apiurl="https://management.chinacloudapi.cn/.../CloudServiceName?api-version=2015-06-01"

应修改为:

apiurl="https://management.chinacloudapi.cn/.../CloudServiceName`?api-version=2015-06-01"

 

 

 

参考资料

Resource Groups - Listhttps://docs.microsoft.com/en-us/rest/api/resources/resource-groups/list

Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorizationhttps://www.cnblogs.com/lulight/p/14279338.html

 

相关文章
|
20天前
|
JSON API 开发工具
【Azure 应用服务】调用Azure REST API来获取 App Service的访问限制信息(Access Restrictions)以及修改
【Azure 应用服务】调用Azure REST API来获取 App Service的访问限制信息(Access Restrictions)以及修改
|
20天前
|
安全 API 网络安全
【Azure API 管理】APIM不能连接到 App Service (APIM cannot connect to APP service)
【Azure API 管理】APIM不能连接到 App Service (APIM cannot connect to APP service)
|
20天前
【Azure Durable Function】PowerShell Activity 函数遇见 Newtonsoft.Json.JsonReaderException: The reader's MaxDepth of 64 has been exceeded.
【Azure Durable Function】PowerShell Activity 函数遇见 Newtonsoft.Json.JsonReaderException: The reader's MaxDepth of 64 has been exceeded.
|
20天前
【Azure Web Job】Azure Web Job执行Powershell脚本报错 The term 'Select-AzContext' is not recognized as the name
【Azure Web Job】Azure Web Job执行Powershell脚本报错 The term 'Select-AzContext' is not recognized as the name
|
20天前
|
API 开发工具 网络架构
【Azure Developer】如何通过Azure Portal快速获取到对应操作的API并转换为Python代码
【Azure Developer】如何通过Azure Portal快速获取到对应操作的API并转换为Python代码
|
20天前
|
存储 机器学习/深度学习 API
【Azure 存储服务】记一次调用Storage Blob API使用 SharedKey Authorization出现的403错误
【Azure 存储服务】记一次调用Storage Blob API使用 SharedKey Authorization出现的403错误
|
20天前
|
存储 JSON API
【Azure 存储服务】使用REST API操作Azure Storage Table,删除数据(Delete Entity)
【Azure 存储服务】使用REST API操作Azure Storage Table,删除数据(Delete Entity)
【Azure 存储服务】使用REST API操作Azure Storage Table,删除数据(Delete Entity)
|
20天前
|
存储 C# Python
【Azure Storage Account】Azure 存储服务计算Blob的数量和大小的PowerShell代码
【Azure Storage Account】Azure 存储服务计算Blob的数量和大小的PowerShell代码
|
20天前
|
存储 Kubernetes API
【APIM】Azure API Management Self-Host Gateway是否可以把请求的日志发送到Application Insights呢?让它和使用Azure上托管的 Gateway一样呢?
【APIM】Azure API Management Self-Host Gateway是否可以把请求的日志发送到Application Insights呢?让它和使用Azure上托管的 Gateway一样呢?
|
20天前
|
API 网络架构 C++
【Azure Key Vault】使用REST API调用Azure Key Vault Secret的示例步骤
【Azure Key Vault】使用REST API调用Azure Key Vault Secret的示例步骤