Impersonation.impersonate C# (CSharp) Méthode

impersonate() public static méthode

impersonates a user based on username/password provided. executed method after impersonation and then reverts impersonation when task/method is complete.
public static impersonate ( string userName, string password, string domain, Action action, int logonType = 2, int logonProvider ) : void
userName string username to impersonate
password string password for user account
domain string domain of user to impersonate
action Action method to invoke after impersonation
logonType int LogonType to use, defaulted to Network
logonProvider int LogonProvider type, defaulted to default
Résultat void
    		public static void impersonate(string userName, string password, string domain, Action action, int logonType = 2, int logonProvider = 0)
    		{
    			//elevate privileges before doing file copy to handle domain security
    			WindowsImpersonationContext context = null;
    			IntPtr userHandle = IntPtr.Zero;
    			try
    			{
    				Console.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);
    				// Call LogonUser to get a token for the user
    				bool loggedOn = NativeMethods.LogonUser(userName,
    											domain,
    											password,
    											logonType,
    											logonProvider,
    											ref userHandle);
    				if (!loggedOn)
    				{
    					Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
    				}
    
    				// Begin impersonating the user
    				context = WindowsIdentity.Impersonate(userHandle);
    
    				Console.WriteLine("windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);				
    				//execute actions under impersonated user
    				action();
    			}
    			catch (Exception ex)
    			{
    				Console.WriteLine("Exception impersonating user: " + ex.Message);
    			}
    			finally
    			{
    				// Clean up
    				if (context != null)
    				{
    					context.Undo();
    				}
    
    				if (userHandle != IntPtr.Zero)
    				{
    					NativeMethods.CloseHandle(userHandle);
    				}
    			}
    		}
Impersonation