代码之家  ›  专栏  ›  技术社区  ›  silent

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

  •  1
  • silent  · 技术社区  · 7 年前

    有没有一种方法可以使用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 回复  |  直到 7 年前
        1
  •  1
  •   silent    7 年前

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

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

    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图。如果需要调用另一个API(即时间序列洞察),则需要注册一个表示脚本的新应用程序(本机应用程序)(需要在脚本$clientid变量中指定此新应用程序的guid),并授予它调用API的委托权限。还要确保在$authority变量中指定租户名称,在$resourceAppIDuri变量中指定api-guid或uri。