Reputation: 33
I am developing a .NET Core 3.1 API that is trying to connect to Exchange Online by calling Powershell from behind a Proxy that you need to authenticate with.
If I run the below Powershell script in Powershell it connects without an issue and pulls back the required data:
$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
If I try and run the same script above in a script file (c:\temp\exchangeonline.ps1) from within C# I get the following error - I have tried using C# with PS (i.e. not using a PS script file) and I get the same error:
{System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The remote server returned an error: (407) Proxy Authentication Required
The C# code is as follows:
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();
......}
The error variable shows the above error I displayed re: the proxy authentication issue..
Any ideas how I can get this working via the proxy where the proxy requires authentication? This using C# of course. Also, we have to use MFA authentication with ExchangeOnline...
Thanks, Marcus
Upvotes: 1
Views: 1122