Thursday, October 9, 2008

Executing C# application as a different user

This is conceptually similar to impersonation. But one difference is, in case of impersonation, there is much more control - we can execute different parts of an application work with different privileges. What we are discussing here is applicable only at the application level. The application will be executed as a different user. This is similar to executing an application by selecting "Run as..." from the Explorer context menu.

Code snippet is given below. First, add the following lines to the class.

using System.Diagnostics;
using System.Security;

Function for executing the application as different user:

private void RunAs(string userName,
                        string password,
                        string domain,
                        string application)
{
    try
    {
        using (Process proc = new Process())
        {
            proc.StartInfo.FileName = application;

            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            proc.StartInfo.UserName = userName;
            proc.StartInfo.Password = GetPassword(password);
            proc.StartInfo.Domain = domain;

            proc.Start();

            proc.WaitForExit();

            proc.Close();                   
        }
    }
    catch
    {
        throw;
    }
}

Helper function - GetPassword() - used for getting the secured password from plaintext password:

private  SecureString GetPassword(string password)
{
    Char[] input = password.ToCharArray();
    SecureString securePassword = new SecureString();

    for (int i = 0; i < input.Length; i++)
    {
        securePassword.AppendChar(input[i]);
    }
    securePassword.MakeReadOnly();

    return securePassword;
}

If the computer is in a workgroup (instead of domain), pass empty string to the domain parameter of RunAs().

No comments: