若要访问 Azure REST API(例如 Log Analytics API)或发送自定义指标,可以根据客户端 ID 和机密生成授权令牌。 然后,在 REST API 请求中传递令牌。 本文介绍如何注册客户端应用和创建客户端密码,以便生成令牌。
注册应用程序
使用 Azure 门户、Azure CLI 或 PowerShell 创建服务主体并注册应用。
若要注册应用,请打开 Azure 门户中的“Active Directory 概述”页。
从侧栏中选择“应用注册”。
选择“新建注册”
在“注册应用程序”页上,输入应用程序的名称。
选择“注册”
在应用的概述页上,选择“证书和机密”
记下“应用程序(客户端) ID”。 它用于获取令牌的 HTTP 请求中。
在“客户端密码”选项卡上,选择“新建客户端密码”
输入说明并选择“添加”
复制并保存客户端密码值。
注意
客户端密码值只能在创建后立即查看。 请确保在离开该页面之前保存该机密。
运行以下脚本以创建服务主体和应用。
az ad sp create-for-rbac -n <Service principal display name>
响应如下所示:
{
"appId": "00001111-aaaa-2222-bbbb-3333cccc4444",
"displayName": "AzMonAPIApp",
"password": "123456.ABCDE.~XYZ876123ABcEdB7169",
"tenant": "aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e"
}
重要
输出包括必须保护的凭据。 请确保没有将这些凭据包含在代码中,也没有将凭据签入到源代码管理中。
为要使用 API 访问的资源添加角色和范围
az role assignment create --assignee <`appId`> --role <Role> --scope <resource URI>
以下示例中的 CLI 将 Reader
角色分配给 rg-001
资源组中所有资源的服务主体:
az role assignment create --assignee 00001111-aaaa-2222-bbbb-3333cccc4444 --role Reader --scope '\/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/rg-001'
有关使用 Azure CLI 创建服务主体的详细信息,请参阅使用 Azure CLI 创建 Azure 服务主体。
以下示例脚本演示如何通过 PowerShell 创建 Microsoft Entra 服务主体。 有关更详细的演练,请参阅使用 Azure PowerShell 创建用于访问资源的服务主体
$subscriptionId = "{azure-subscription-id}"
$resourceGroupName = "{resource-group-name}"
# Authenticate to a specific Azure subscription.
Connect-AzAccount -SubscriptionId $subscriptionId
# Password for the service principal
$pwd = "{service-principal-password}"
$secureStringPassword = ConvertTo-SecureString -String $pwd -AsPlainText -Force
# Create a new Azure Active Directory application
$azureAdApplication = New-AzADApplication `
-DisplayName "My Azure Monitor" `
-HomePage "https://localhost/azure-monitor" `
-IdentifierUris "https://localhost/azure-monitor" `
-Password $secureStringPassword
# Create a new service principal associated with the designated application
New-AzADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
# Assign Reader role to the newly created service principal
New-AzRoleAssignment -RoleDefinitionName Reader `
-ServicePrincipalName $azureAdApplication.ApplicationId.Guid
后续步骤
需使用访问控制 (IAM) 将应用分配到你想要访问的资源的角色,才能使用应用、客户端 ID 和机密生成令牌。 角色将取决于资源类型和要使用的 API。
例如,
有关详细信息,请参阅使用 Azure 门户分配 Azure 角色
分配角色后,可以使用应用、客户端 ID 和客户端密码生成持有者令牌来访问 REST API。
注意
使用 Microsoft Entra 身份验证时,Azure Application Insights REST API 识别新的基于角色的访问控制 (RBAC) 权限,可能需要最多 60 分钟。 权限在传播时,REST API 调用可能会失败,错误代码 403。