Search code examples
c#windows-serviceswmi

Retrieve and use service 'Log on as' credentials in C#


I'm currently writing a Windows Service which will be required to interact with an on-premise Exchange server. Quite rightly, we've come to the conclusion that hard-coding the Exchange credentials is a very bad idea, but so is storing them in a config file in plain text. We've come to the conclusion that creating a service account that owns the mailbox in question should satisfy our requirements, however I've hit the following problem:

I've started to use a ManagementObjectSearcher to get the Username of the account running a service on my PC, however I'm not sure how to, or even if, I can get the password. I've tried this:

    class Program
{

    public static ManagementObjectSearcher Searcher = new ManagementObjectSearcher(new SelectQuery("select * from Win32_Service where name = 'netlogon'"));

    static void Main(string[] args)
    {

        ManagementObjectCollection Response = Searcher.Get();

        Console.WriteLine(Response.Count);

        foreach (ManagementObject Item in Response)
        {
            Console.WriteLine(Item.ToString());
        }

        Console.ReadLine();
    }

}

Unfortunately, I don't get a Password back. There's some suggestion from the EWS API documentation (https://msdn.microsoft.com/en-us/library/office/dn626019(v=exchg.150).aspx) that I can grab the credentials of the currently logged in user, but I looked through the referenced code samples and can find no suggestion of how this is doable.

For clarity, I can get the username, that's fine. I need the password... Any help would be appreciated!


Solution

  • It seems there are two acceptable answers:

    One that @rene proposed involves using the Microsoft CredentialCache type to return the network credentials of the currently logged in user, which in a service context seems to just be the 'log on as' credentials. Details found here: https://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultnetworkcredentials(v=vs.110).aspx

    The second is one that I Found, which involves simply not adding credentials to the EWS API ExchangeService type, in which case the credentials of the users running the service will automatically be passed through to Exchange.