首页 > 解决方案 > 从当前用户的 powershell 获取 Azure Active Directory 资源访问令牌?

问题描述

有没有办法使用 PowerShell 为某个 Azure 资源(在我的情况下为时序见解)获取基于 Azure Active Directory 的令牌?不是为了某些服务原则,而是为了当前用户。在 .NET (c#) 中,现在很容易使用托管服务标识

using Microsoft.Azure.Services.AppAuthentication;

var azureServiceTokenProvider = new AzureServiceTokenProvider();
string token = await azureServiceTokenProvider.GetAccessTokenAsync("https://api.timeseries.azure.com/");

那么这在 PowerShell 中也可以实现吗?到目前为止,我看到的任何示例总是使用服务原则,或者只是为当前用户提供 Azure 管理 API 的令牌。

标签: powershellazureazure-active-directory

解决方案


如果您的 PowerShell 脚本在已加入本地域的 Active Directory 的计算机上运行,​​该计算机已连接到企业网络,并且运行脚本的用户是同步到 Azure Active Directory 的域用户,那么您可以使用覆盖使用集成 Windows 身份验证的 ADAL AcquireTokenAsync 。

此 PowerShell 示例获取当前用户调用 Graph 的令牌:

add-type -path "\Microsoft.IdentityModel.Clients.ActiveDirectory.3.13.4\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$resourceAppIdURI = "https://graph.windows.net"
$UserCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList "user@contoso.com"
$authority = "https://login.windows.net/TENANT.onmicrosoft.com" 
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority,$false
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext,$resourceAppIdURI,$clientId,$UserCredential).result

在示例中,客户端 ID 是众所周知的 PowerShell GUID,资源是 AAD Graph。如果您需要调用另一个 API(即 Time Series Insights),您将需要注册一个表示脚本的新应用程序(本机应用程序)(您需要在脚本中指定此新应用程序的 GUID,$clientId 变量)和授予它调用 API 的委托权限。还要确保在 $authority 变量中指定您的租户名称,并在 $resourceAppIdURI 变量中指定 API GUID 或 URI。


推荐阅读