Exchange Online Powershell BasicAuthToOAuth 无法与 WSManConnectionInfo 配合使用

问题描述 投票:0回答:2

我们的代码当前使用 WSManConnectionInfo 类连接到 O365。我们使用基本身份验证并正在尝试升级到现代身份验证。我关闭了租户中的基本身份验证。按照这里的指南,https://www.michev.info/Blog/Post/2997/connecting-to-exchange-online-powershell-via-client-secret-fl...,我能够成功连接在 PowerShell 中,通过获取访问令牌并使用 New-PSSession cmdlet。我使用以下命令:

Add-Type -Path 'C:\Program Files\WindowsPowerShell\Modules\AzureAD\2.0.2.140\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
 
$authContext45 = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList " https://login.windows.net/mytenant.onmicrosoft.com"
$secret = Get-ChildItem cert://localmachine/my/thumbprint
$CAC = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate]::new(appId,$secret)
$authenticationResult = $authContext45.AcquireTokenAsync("https://outlook.office365.com",$CAC)

$token = $authenticationResult.Result.AccessToken
$Authorization = "Bearer {0}" -f $Token
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Ctoken = New-Object System.Management.Automation.PSCredential -ArgumentList "OAuthUser@tenantGUID",$Password
 
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true -Credential $Ctoken -Authentication Basic -AllowRedirection -Verbose
Import-PSSession $Session

但是,当我尝试使用 C# WSManConnectionInfo 执行相同的操作时,每当我尝试打开运行空间时,都会收到此奇怪的错误:

System.Management.Automation.Remoting.PSRemotingTransportException H结果=0x80131501 Message=连接到远程服务器 Outlook.office365.com 失败,并出现以下错误消息: WS-Management 服务无法处理该请求。在 Outlook.office365.com 计算机上的 WSMan: 驱动器中找不到 https://schemas.microsoft.com/powershell/Microsoft.Exchange 会话配置。有关详细信息,请参阅 about_Remote_Troubleshooting 帮助主题。 这是代码:

    public static Collection<PSObject> GetUsersUsingOAuthPublic()
    {
        var authContext = new AuthenticationContext("https://login.windows.net/mytenant.onmicrosoft.com");
        X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);

        certStore.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, false);
        certStore.Close();
        var cac = new ClientAssertionCertificate(appId, certCollection[0]);
        var authResult = authContext.AcquireTokenAsync("https://outlook.office365.com", cac);

        var token = authResult.Result.AccessToken;
        string auth = string.Format("Bearer {0}", token);
        System.Security.SecureString password = new System.Security.SecureString();

        foreach (char c in auth)
        {
            password.AppendChar(c);
        }

        PSCredential psCredential = new PSCredential(string.Format("OAuthUser@{0}", tenantId), password);

        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
            new Uri("https://outlook.office365.com/powershell-liveid?BasicAuthToOAuthConversion=true"),
            "https://schemas.microsoft.com/powershell/Microsoft.Exchange",
            psCredential
            );
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
        connectionInfo.SkipCACheck = true;
        connectionInfo.SkipCNCheck = true;

        using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            return GetUserInformation(10, runspace);
        }
    }

我像这样打开运行空间:

    public static Collection<PSObject> GetUserInformation(int count, Runspace runspace)
    {
        using (PowerShell powershell = PowerShell.Create())
        {
            powershell.AddCommand("Get-Users");
            powershell.AddParameter("ResultSize", count);
            runspace.Open();
            powershell.Runspace = runspace;
            return powershell.Invoke();
        }
    }

例外情况: Image of exception

c# powershell oauth-2.0 office365 powershell-remoting
2个回答
0
投票

我们也一直在解决这个问题,并且我们能够让它发挥作用。在此测试用例中,我们使用密钥而不是 accessToken 的证书,但这应该不重要。

第一个区别是 uri 应该如下所示:

Uri psURI = new($"https://outlook.office365.com/powershell-liveid?BasicAuthToOAuthConversion=true&email=SystemMailbox%7bbb558c35-97f1-4cb9-8ff7-d53741dc928c%7d%40{msDomain}");

第二个更改是架构,通过此更改,您无需传递架构的完整 url,仅传递最后一部分:

WSManConnectionInfo connectionInfo = new(psURI, "Microsoft.Exchange", psCredential)
{
    AuthenticationMechanism = AuthenticationMechanism.Basic,    
    SkipCACheck = true,
    SkipCNCheck = true
};

不要传入“https://schemas.microsoft.com/powershell/Microsoft.Exchange”,只需传入“Microsoft.Exchange”

以下是允许我们针对禁用基本身份验证的租户运行 Get-Mailbox 的完整代码:

string clientId = "";
string tenantId = "";
string secret = "";
string upn = "[email protected]";
string msDomain = "YOURDOMAIN.onmicrosoft.com";


IConfidentialClientApplication thisApp = ConfidentialClientApplicationBuilder.Create(clientId)
    .WithClientSecret(secret)
    .WithAuthority($"https://login.windows.net/{msDomain}/")
    .Build();
AuthenticationResult accessToken = await thisApp.AcquireTokenForClient(new[] { $"https://outlook.office365.com/.default" }).ExecuteAsync();

//Bearer Header
string auth = $"Bearer {accessToken.AccessToken}";
SecureString password = GetSecureString(auth);

PSCredential psCredential = new($"OAuthUser@{tenantId}", password);

Uri psURI = new("https://outlook.office365.com/powershell-liveid?BasicAuthToOAuthConversion=true&email=SystemMailbox%7bbb558c35-97f1-4cb9-8ff7-d53741dc928c%7d%40{domain}");

WSManConnectionInfo connectionInfo = new(psURI, "Microsoft.Exchange", psCredential)
{
    AuthenticationMechanism = AuthenticationMechanism.Basic,    
    SkipCACheck = true,
    SkipCNCheck = true,
};

using Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
using PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;

ps.AddCommand("Get-Mailbox");
ps.AddParameter("Identity", upn);

var results = await ps.InvokeAsync();

0
投票

据我所知,微软不支持此功能。要使用 MFA 连接到 Exchange Online,您应该使用此处描述的受支持的方法之一:https://learn.microsoft.com/en-gb/powershell/exchange/connect-to-exchange-online-powershell?view=exchange -ps

请检查我的答案,以无人值守脚本的形式使用证书指纹进行连接,这最接近您想要实现的目标: 使用证书和 C# 连接到 Exchange Online

您的其他连接选项是:

  • 使用基于浏览器的单点登录进行交互式脚本编写
  • 基于设备的登录
  • 内嵌凭证

我上面的链接中描述了所有这些选项

© www.soinside.com 2019 - 2024. All rights reserved.