ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
2,824 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
We have register an application with permission Delegated permission: Exchange.Manage, Application permission: Exchange.ManageAsApp
When try to open Runspace using that token to execute Remote EXO V2 command but with that system returns error: Connecting to remote server outlook.office365.com failed with the following error message : For more information, see the about_Remote_Troubleshooting Help topic.
We use below code to connect:
PSCredential pSCredential = new PSCredential(inputUserName, new NetworkCredential("", inputPassword).SecurePassword);
string MailboxName = pSCredential.UserName;
string scope = "https://outlook.office365.com/.default";
string ClientId = Configuration.Client_Id;
string clientSecret = Configuration.ClientSecret;
HttpClient Client = new HttpClient();
var TenantId = ((dynamic)JsonConvert.DeserializeObject(Client.GetAsync("https://login.microsoftonline.com/" + MailboxName.Split('@')[1] + "/v2.0/.well-known/openid-configuration").Result.Content.ReadAsStringAsync().Result)).authorization_endpoint.ToString().Split('/')[3];
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId).WithClientSecret(clientSecret).WithTenantId(TenantId).Build();
var TokenResult = app.AcquireTokenForClient(new[] { scope }).ExecuteAsync().Result;
System.Security.SecureString secureString = new System.Security.SecureString();
foreach (char c in ("bearer " + TokenResult.AccessToken))
secureString.AppendChar(c);
String WSManURIConnectionString = "https://outlook.office365.com/powershell-liveid?DelegatedOrg=" + MailboxName.Split('@')[1] + "&BasicAuthToOAuthConversion=true";
PSCredential credential = new PSCredential(MailboxName, secureString);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(WSManURIConnectionString), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 10;
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
{
runspace.Close();
}
runspace.Open();
// Make a Get-EXOMailbox requst using the Server Argument
Command gmGetMailbox = new Command("Get-EXOMailbox");
gmGetMailbox.Parameters.Add("ResultSize", "Unlimited");
Pipeline plPileLine = runspace.CreatePipeline();
plPileLine.Commands.Add(gmGetMailbox);
Collection RsResultsresults = plPileLine.Invoke();
plPileLine.Stop();
plPileLine.Dispose();