我正在开发一个 .NET Core 3.1 API,它试图通过从您需要进行身份验证的代理后面调用 Powershell 来连接到 Exchange Online。
如果我在 Powershell 中运行以下 Powershell 脚本,它会毫无问题地连接并拉回所需的数据:
$certthumb="xxxxxx"
$appid="xxxxxx"
$org="xxxxxx"
$proxyserver="xxxxxx:8080"
$webproxypsd = "xxxxxx"
$secureWebproxypsd = $webproxypsd | ConvertTo-SecureString -AsPlainText -Force
$proxyCredential = new-object System.Management.Automation.PSCredential ("xxxxxxx",$secureWebproxypsd)
Set-ExecutionPolicy Unrestricted -force
$proxysettings = New-PSSessionOption -ProxyAccessType IEConfig -ProxyCredential $proxyCredential -ProxyAuthentication Basic
$w=New-Object System.Net.WebClient
$w.Proxy.Credentials = $proxyCredential
import-module ExchangeOnlineManagement
Connect-exchangeonline -CertificateThumbPrint $certthumb -AppID $appid -organization $org -PSSessionOption $proxysettings
Get-MailUser "xxxxxx" |fl exchangeguid
如果我尝试在 C# 中的脚本文件 (c:\temp\exchangeonline.ps1) 中运行上述相同的脚本,我会收到以下错误 - 我已尝试将 C# 与 PS 一起使用(即不使用 PS 脚本文件)并且我得到同样的错误:
{System.AggregateException:发生一个或多个错误。---> System.Net.Http.HttpRequestException: 发送请求时出错。---> System.Net.WebException:远程服务器返回错误:(407)需要代理身份验证
C#代码如下:
using (Runspace localRunSpacePool = RunspaceFactory.CreateRunspace())
{
localRunSpacePool.Open();
using (var PowerShellInstance = ConnectToExchangeOnline(localRunSpacePool))
{.....}
public PowerShell ConnectToExchangeOnline(Runspace localRunSpacePool)
{
var PowerShellInstance = PowerShell.Create();
PowerShellInstance.Runspace = localRunSpacePool;
var error = localRunSpacePool.SessionStateProxy.PSVariable.GetValue("Error");
var scriptfile = "c:\\temp\\exchangeonline.ps1";
PowerShellInstance.AddScript(scriptfile);
var scriptresult = PowerShellInstance.Invoke();
error = localRunSpacePool.SessionStateProxy.PSVariable.GetValue("Error");
PowerShellInstance.Commands.Clear();
......}
错误变量显示了我显示的上述错误:代理身份验证问题..
有什么想法可以通过代理需要身份验证的代理来实现吗?这当然使用 C#。此外,我们必须使用 ExchangeOnline 的 MFA 身份验证...
谢谢,马库斯