'Calling Exchange PowerShell in C#

I have an application that allows users who would not otherwise have access to Exchange to perform some delegate functions. This all works fine for users who are on standard domain-joined machines. However we are getting an increasing number of devices built by MEM (Intune) that, while managed according to policies, aren't domain-members. This causes an issue when I attempt to create an Exchange PowerShell session in code because of the Kerberos authentication used. This is an example of some code from the application:

internal static bool UpdateMailbox(string identity, out string reply)
{
    reply = string.Empty;
    try
    {
        string server = DatabaseManager.GetConfigOption("ExchangePowerShellURI"); // http://exc16-01.domain.com/PowerShell
        string uname = DatabaseManager.GetConfigOption("ADUser");  // [email protected]
        SecureString password = GetPassword(); // makes a SecureString for the user password
        PSCredential creds = new PSCredential(uname, password);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(server), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", creds);
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
        using (Runspace rs = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            rs.Open();
            using (PowerShell ps = PowerShell.Create())
            {
                ps.Runspace = rs;
                
                // do stuff with PowerShell
                
                return true;
            }
        }
    }
    catch (Exception ex)
    {
        reply = ex.Message;
        return false;
    }
}

I have thought about using certificate-based authentication instead, but I don't know if this will work with Exchange PowerShell, or how to alter my code to use that instead of Kerberos. I know I could change the WinRM clients/servers to allow unencrypted traffic and use Basic authentication, but I would rather not do this unless there is no other choice.

I'd be grateful for any advice on how I could get this to work for the non-domain-joined devices, even if it turns out that Basic is the only option.

If its relevant to anything I'm asking, we are using Exchange 2016 on-premises.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source