Skip to content

Instantly share code, notes, and snippets.

@gscales
Created July 24, 2020 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gscales/66cacbef64087a5c89587f1ce6a739fa to your computer and use it in GitHub Desktop.
Save gscales/66cacbef64087a5c89587f1ce6a739fa to your computer and use it in GitHub Desktop.
Exchange Online Remote Powershell MSAL ROPC
PSCredential pSCredential = new PSCredential("user@blah.onmicrosoft.com", new NetworkCredential("", "pass##").SecurePassword);
string MailboxName = pSCredential.UserName;
string scope = "https://outlook.office365.com/.default";
string ClientId = "a0c73c16-a7e3-4564-9a95-2bdf47383716";
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];
PublicClientApplicationBuilder pcaConfig = PublicClientApplicationBuilder.Create(ClientId);
pcaConfig.WithTenantId(TenantId);
var TokenResult = pcaConfig.Build().AcquireTokenByUsernamePassword(new[] { scope }, pSCredential.UserName, pSCredential.Password).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 = 4;
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
// Make a Get-Mailbox requst using the Server Argument
Command gmGetMailbox = new Command("get-mailbox");
gmGetMailbox.Parameters.Add("ResultSize", "Unlimited");
Pipeline plPileLine = runspace.CreatePipeline();
plPileLine.Commands.Add(gmGetMailbox);
Collection<PSObject> RsResultsresults = plPileLine.Invoke();
Dictionary<string, PSObject> gmResults = new Dictionary<string, PSObject>();
foreach (PSObject obj in RsResultsresults)
{
Console.WriteLine(obj.Members["WindowsEmailAddress"].Value.ToString());
}
Command gmGetUser = new Command("get-user");
plPileLine.Stop();
plPileLine.Dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment