C# 从Powershell获取Azure Active Directory访问令牌

C# 从Powershell获取Azure Active Directory访问令牌,c#,powershell,azure,azure-active-directory,access-token,C#,Powershell,Azure,Azure Active Directory,Access Token,我有一个应用程序Id和一个在注册Azure Active Directory应用程序后在Azure门户中生成的密钥 有了这一对和我的Powershell脚本,我想生成一个访问令牌,我将在HTTP请求的脚本中使用它 我可以使用C#(参见下面的代码)获取访问令牌,但我不确定如何在Powershell中执行类似操作。Powershell中是否已经内置了任何东西?如果没有,有人能告诉我一个解决方案吗?我很确定我不是唯一一个有这个问题的人 public static async Task<strin

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

有了这一对和我的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;
}
publicstaticasync任务GetAccessTokenAsync(stringclientid、stringappkey、stringresourceid)
{
字符串aadInstance=”https://login.microsoftonline.com/{0}";
字符串tenant=“.onmicrosoft.com”;
string authority=string.Format(CultureInfo.InvariantCulture,aadInstance,tenant);
AuthenticationContext authContext=新的AuthenticationContext(授权);
ClientCredential ClientCredential=新的ClientCredential(clientId,appKey);
AuthenticationResult AuthenticationResult=null;
authenticationResult=等待authContext.AcquireTokenAsync(resourceId,clientCredential);
返回authenticationResult.AccessToken;
}

> p>我写了我认为是一个很好的教程,就这样:

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

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

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

# Load ADAL
Add-Type -Path ".\ADAL\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"\
从这里开始,调用所有ADAL函数就像在标准C#应用程序中一样简单

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

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


根据您的具体需要,这两个选项中的一个应该适合您。让我知道这是否有帮助

谢谢!将此标记为有效问题,因为它帮助我找到了与您提供的类似的其他文档。