简体   繁体   中英

Connect to Exchange Online in C# with PowerShell cmdlet using a key on encrypted password

I would like to access Exchange online from C#, such as a web application to provide management flexibility. Normally, I use the powershell script below.

//the key and password was changed

IF ($session.state -ne 'Opened') {
    # encryption key
    $key = (3,4,12,3,56,34,211,22,1,1,22,23,42,54,33,233,81,34,2,27,116,5,35,43)

    $adminUser = "admin@domain.onmicrosoft.com" 
    $adminPwd = "76492d1974683f0423413b12570a5345MgB8AGgAZgB0AE4AeABlAG4AbgB5AHYATABwAE4AbwB5AGgAUABtAHoAbwBYAEEAPQA9AHhn208edA8nE973VsDji2wAMwA3AGMAYQBkADgAMgA2ADYAZABkADIAMQA1AGEAMQBiAGQAOQAQBiADEANAAyAGEANAA=" | ConvertTo-SecureString -Key $Key
    $psCred = New-Object System.Management.Automation.PsCredential $adminUser,$adminPwd 

    $O365Url = "https://outlook.office365.com/powershell-liveid/" 

    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $O365Url -Credential $psCred -Authentication basic -AllowRedirection 

    Import-PSSession $Session -AllowClobber
}
Else {
    Write-Host 'Opened session'

}

// do something

Remove-PSSession $Session -AllowClobber

Now I try to do the same in C#. I can connect when the password is in clear text. I don't understand how to include my encryption key. Here the code:

byte[] key = {3,4,12,3,56,34,211,22,1,1,22,23,42,54,33,233,81,34,2,27,116,5,35,43};

string adminUser = "admin@domain.onmicrosoft.com" 
string adminPwd = "76492d1974683f0423413b12570a5345MgB8AGgAZgB0AE4AeABlAG4AbgB5AHYATABwAE4AbwB5AGgAUABtAHoAbwBYAEEAPQA9AHhn208edA8nE973VsDji2wAMwA3AGMAYQBkADgAMgA2ADYAZABkADIAMQA1AGEAMQBiAGQAOQAQBiADEANAAyAGEANAA=";
string O365Url = "https://outlook.office365.com/powershell-liveid/";

SecureString adminPwdSecure = new SecureString();
PSObject SessionHolder = null;

foreach (char c in adminPwd.ToCharArray())
    adminPwdSecure.AppendChar(c);

adminPwdSecure.MakeReadOnly();

PSCredential credential = new PSCredential(adminUser, adminPwdSecure);

Runspace runspace = RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();

PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(O365Url));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");
powershell.Commands = command;

runspace.Open();
powershell.Runspace = runspace;
Collection<PSObject> result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
    throw new Exception("Fail to establish the connection");
}
else
{
    //Success to establish the connection
    SessionHolder = result[0];
}

PSCommand ImportSession = new PSCommand();
ImportSession.AddCommand("Import-PSSession");
ImportSession.AddParameter("Session", SessionHolder);
powershell.Commands = ImportSession;
powershell.Invoke();

// do something

PSCommand RemoveSession = new PSCommand();
RemoveSession.AddCommand("Remove-PSSession");
RemoveSession.AddParameter("Session", SessionHolder);
powershell.Commands = RemoveSession;
powershell.Invoke();

You can try to create your encryption key like so:

    byte[] key = { 3, 4, 12, 3, 56, 34, 211, 22, 1, 1, 22, 23, 42, 54, 33, 233, 81, 34, 2, 27, 116, 5, 35, 43 };

    string adminUser = "admin@domain.onmicrosoft.com";
    string adminPwd = "76492d1974683f0423413b12570a5345MgB8AGgAZgB0AE4AeABlAG4AbgB5AHYATABwAE4AbwB5AGgAUABtAHoAbwBYAEEAPQA9AHhn208edA8nE973VsDji2wAMwA3AGMAYQBkADgAMgA2ADYAZABkADIAMQA1AGEAMQBiAGQAOQAQBiADEANAAyAGEANAA=";
    string O365Url = "https://outlook.office365.com/powershell-liveid/";

    PSObject SessionHolder = null;

    Runspace runspace = RunspaceFactory.CreateRunspace();
    PowerShell powershell = PowerShell.Create();

    runspace.Open();
    powershell.Runspace = runspace;

    // >>> Create $adminPwdSecure encrypted variable using PowerShell:
    powershell.AddCommand("ConvertTo-SecureString")
        .AddParameter("String", adminPwd)
        .AddParameter("Key", key)
        .AddCommand("New-Variable")
        .AddParameter("Name", "adminPwdSecure")
        .Invoke();

    // >>> Read $adminPwdSecure variable from session state:
PSCredential credential = new PSCredential(adminUser, (SecureString)((PSObject)pwsh.Runspace.SessionStateProxy.PSVariable.GetValue("adminPwdSecure")).BaseObject);

    PSCommand command = new PSCommand();
    command.AddCommand("New-PSSession");
    command.AddParameter("ConfigurationName", "Microsoft.Exchange");
    command.AddParameter("ConnectionUri", new Uri(O365Url));
    command.AddParameter("Credential", credential);
    command.AddParameter("Authentication", "Basic");
    powershell.Commands = command;

    Collection<PSObject> result = powershell.Invoke();
    if (powershell.Streams.Error.Count > 0 || result.Count != 1)
    {
        throw new Exception("Fail to establish the connection");
    }
    else
    {
        //Success to establish the connection
        SessionHolder = result[0];
    }

    PSCommand ImportSession = new PSCommand();
    ImportSession.AddCommand("Import-PSSession");
    ImportSession.AddParameter("Session", SessionHolder);
    powershell.Commands = ImportSession;
    powershell.Invoke();

    // do something

    PSCommand RemoveSession = new PSCommand();
    RemoveSession.AddCommand("Remove-PSSession");
    RemoveSession.AddParameter("Session", SessionHolder);
    powershell.Commands = RemoveSession;
    powershell.Invoke();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM