impersonate c#

using  System;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace impersonate
{
    
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, 2ref 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
    }
}



  ImpersonateConnection i 
= new ImpersonateConnection();
   i.impersonateValidUser(
"stswordman""domain1 ""p@s5word"));
//the following code would be run under domain1\stswormdan ‘s context
//
  i.undoImpersonation();//revert to original context
原文地址:https://www.cnblogs.com/stswordman/p/1308250.html