【问题标题】:Get Azure Active Directory Access Token from Powershell从 Powershell 获取 Azure Active Directory 访问令牌
【发布时间】:2018-02-17 20:56:50
【问题描述】:

注册 Azure Active Directory 应用程序后,我在 Azure 门户中生成了一个应用程序 ID 和一个密钥。

通过这对和我的 Powershell 脚本,我想生成一个访问令牌,我将在 HTTP 请求的脚本中使用它。

我可以使用 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;
}

【问题讨论】:

    标签: c# powershell azure azure-active-directory access-token


    【解决方案1】:

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

    Azure AD Authentication with PowerShell and ADAL

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

    你可以在 GitHub here 上找到我所有的脚本。

    诀窍在于,您实际上可以使用 PowerShell 的 Add-Type 函数加载 ADAL 的 .NET 程序集:

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

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

    话虽如此,您可能还想查看官方 AAD PowerShell 模块:

    Azure Active Directory PowerShell Version 2

    您可以将 Azure Active Directory PowerShell 模块版本 2 用于 Azure AD 管理任务,例如用户管理、域 管理和配置单点登录。

    根据您在此处的确切需求,这两个选项之一应该适合您。让我知道这是否有帮助!

    【讨论】:

    猜你喜欢
    • 2020-05-25
    • 1970-01-01
    • 2023-03-19
    • 2023-02-01
    • 1970-01-01
    • 2019-11-06
    • 2018-03-24
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多