从powershell为当前用户获取Azure Active Directory资源访问令牌?

时间:2018-05-29 09:25:25

标签: powershell azure azure-active-directory

有没有办法使用PowerShell为某个Azure资源(在我的案例中为Time Series Insights)获取基于Azure Active Directory的令牌?不是针对某些服务原则,而是针对当前用户。在.NET(c#)中,现在很容易使用Managed Service Identity

using Microsoft.Azure.Services.AppAuthentication;

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

这样的东西在PowerShell中也可行吗?到目前为止,我看到的任何示例始终使用服务原则,或者仅为当前用户提供Azure管理API的令牌。

1 个答案:

答案 0 :(得分:1)

如果PowerShell脚本在加入内部域上的Active Directory的计算机上运行,​​则计算机将连接到企业网络,运行该脚本的用户是同步到Azure Active Directory的域用户,然后是可以使用覆盖ADAL AcquireTokenAsync,它使用集成的Windows身份验证。

此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(即时间序列见解),您将需要注册一个代表该脚本的新应用程序(本机应用程序)(您需要在脚本中指定此新应用程序的GUID,$ clientId变量)和给它委派的权限来调用API。还要确保在$ authority变量中指定租户名称,并在$ resourceAppIdURI变量中指定API GUID或URI。