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

从Powershell获取Azure Active Directory访问令牌

  •  3
  • user3587624  · 技术社区  · 7 年前

    我有一个应用程序Id和一个在注册Azure Active Directory应用程序后在Azure门户中生成的密钥。

    我可以使用C#(请参阅下面的代码)获取访问令牌,但我不确定如何在Powershell中执行类似操作。Powershell中是否已经内置了什么?如果没有,有人能告诉我一个解决方案吗?我很确定我不是唯一一个有这个问题的人。

    public static async Task<string> GetAccessTokenAsync(string clientId, string appKey, string resourceId)
    {
         string aadInstance = "https://login.microsoftonline.com/{0}";
         string tenant = "<TENANT>.onmicrosoft.com";
         string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
         AuthenticationContext authContext = new AuthenticationContext(authority);
         ClientCredential clientCredential = new ClientCredential(clientId, appKey);
    
         AuthenticationResult authenticationResult = null;       
         authenticationResult = await authContext.AcquireTokenAsync(resourceId, clientCredential);
    
         return authenticationResult.AccessToken;
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Shawn Tabrizi    7 年前

    我写了一篇我认为很好的教程:

    Azure AD Authentication with PowerShell and ADAL

    使用这些脚本,您可以完成身份验证和REST API调用 只有13行PowerShell。运行代码是即时的, 需要几秒钟而不是几分钟。

    here

    诀窍是您可以实际加载。使用PowerShell的ADAL网络组件 Add-Type

    # Load ADAL
    Add-Type -Path ".\ADAL\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"\
    

    从那里,调用所有ADAL函数就像在标准C#应用程序中一样简单。

    话虽如此 ,您可能需要了解的另一件事是官方AAD PowerShell模块:

    Azure Active Directory PowerShell Version 2

    管理和配置单点登录。

    根据您的具体需要,这两个选项中的一个应该适合您。如果有帮助,请告诉我!