日期:2014-05-17  浏览次数:20964 次

Impersonate: use specified credential to execute some code in C#

In some scenarios we need run some code under some specified credential:

1. You want to run a windows service which to copy file to a UNC path, but the IT don't let you to use the domain account to run the service, and the local admin account don't have the permission to access UNC path, in that case you need to use Impersonate

 

2.You want to access some service in your code and only specified account can access it, but the end user can't use this account for some security reason, in that case you need to use Impersonate as well

 

Let's see how to use specified credential to execute some code in C#.

1. Need a ImpersonateConnection class

using System;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace YourNameSpace
{
    public class ImpersonateConnection
    {
        //definition for Impersonation
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
        WindowsImpersonationContext impersonationContext;
        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);
        // ------------------------------
        // impersonate another valid user
        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }

            if (token != IntPtr.Zero)
                CloseHandle(token);

            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);

            return false;
        }

        //unimpersonate validate user
        public void UndoImpersonation()
        {
            impersonationContext.Undo();
        }

        //end of class
    }

}


2. Initalize the ImpersonateConnection before running the code which need to be run under specified credentail(account), and undo it after finishing the code:

 

            ImpersonateConnection impersonateConnection = null;
            bool impersonateSuccessed = false;
            try
            {
                impersonateConnection = new ImpersonateConnection();
                bool impersonateSuccessed = impersonateConnection.ImpersonateValidUser(userName, domain, password);