java系统找不到指定文件怎么解决
293
2022-10-05
【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 ChinaConnect-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"=$accessToken = (Invoke-RestMethod $url -Method 'POST' -Headers $headers -ContentType 'application/x--Body $body ).access_token$authHeader = @{ "Authorization"= "Bearer " + $accessToken "Content-Type"="application/json"}Write-Output "access token acquired successfully"
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!
分类: 【Azure 环境】, 【Azure Developer】
标签: Azure Developer, Azure 环境, AAD Token Powershell, Managed Identity + Microsoft Graph API
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~