【Azure Developer】调用Microsoft Graph API获取Authorization Token,使用的认证主体为 Azure中的Managed Identity(托管标识)

问题描述

在常规情况下,如果要从Azure中获取Authorization Token,需要在Azure AAD中注册一个应用主体,通过Client ID + Client Secret生成Token。但是,当需要直接使用Managed Identity(托管标识)的方式执行Microsoft Graph API来获取Token,如何来实现呢?

 

问题解答

因为Managed Identity不是一个AAD的注册应用,所以需要先通过Powershell命令来为他赋予相应的权限。所以需要对它赋予权限。

 

赋予权限的执行命令为:

# 登录Azure China
Connect-AzureAD -AzureEnvironmentName AzureChinaCloud 

# Get SPN based on MSI Display Name
$msiSpn = (Get-AzureADServicePrincipal -Filter "displayName eq 'managed identity名称'")

# Set well known Graph Application Id
$msGraphAppId = "00000003-0000-0000-c000-000000000000"

# Get SPN for Microsoft Graph
$msGraphSpn = Get-AzureADServicePrincipal -Filter "appId eq '$msGraphAppId'"

# Type Graph App Permissions needed
$msGraphPermission = "Directory.ReadWrite.All","Group.ReadWrite.All","GroupMember.ReadWrite.All"

# Now get all Application Roles matching above Graph Permissions
$appRoles = $msGraphSpn.AppRoles | Where-Object {$_.Value -in $msGraphPermission -and $_.AllowedMemberTypes -contains "Application"}

# Add Application Roles to MSI SPN
$appRoles | % { New-AzureAdServiceAppRoleAssignment -ObjectId $msiSpn.ObjectId -PrincipalId $msiSpn.ObjectId -ResourceId $msGraphSpn.ObjectId  -Id $_.Id }

可以通过以下命令删除权限:

# Get all application permissions for the service principal
$spApplicationPermissions = Get-AzureADServiceAppRoleAssignedTo -ObjectId $msiSpn.ObjectId -All $true | Where-Object { $_.PrincipalType -eq "ServicePrincipal" }

# Remove all permissions
$spApplicationPermissions | ForEach-Object {
    Remove-AzureADServiceAppRoleAssignment -ObjectId $_.PrincipalId -AppRoleAssignmentId $_.objectId
}

 

在配置了Managed Identity的环境中(如Azure VM)中执行Powershell获取Token 示例:

# 使用Identity登录后,获取Context
 $AzureContext = (Connect-AzAccount -Identity -Environment AzureChinaCloud).context


# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext

# Get MS Graph access token 
# Managed Identity
$url = $env:IDENTITY_ENDPOINT 
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" 
$headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER) 
$headers.Add("Metadata", "True") 
$body = @{"resource"=https://microsoftgraph.chinacloudapi.cn/} 
$accessToken = (Invoke-RestMethod $url -Method 'POST' -Headers $headers -ContentType 'application/x-www-form-urlencoded' -Body $body ).access_token
$authHeader = @{
    "Authorization"= "Bearer " + $accessToken
    "Content-Type"="application/json"
}

Write-Output "access token acquired successfully"

 

posted @ 2022-08-01 20:05  路边两盏灯  阅读(208)  评论(0编辑  收藏  举报