public static Impersonator Impersonate( string userName, string domain, string password, ImpersonatorLogonType logonType = ImpersonatorLogonType.InteractiveLogon) { var imp = new Impersonator(userName, domain, password, logonType); imp.Impersonate(imp.logonTyp); return(imp); }
public Impersonator(string UserName, string Domain, string Password, ImpersonatorLogonType logonType = ImpersonatorLogonType.InteractiveLogon) { username = UserName; domain = Domain; password = Password; logonTyp = logonType; }
private WindowsIdentity Logon(ImpersonatorLogonType logonType) { var handle = IntPtr.Zero; const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_NEW_CREDENTIALS = 9; const int LOGON32_PROVIDER_WINNT50 = 5; const int SecurityImpersonation = 2; // attempt to authenticate domain user account try { if (!LogonUser(username, domain, password, (int)logonType, LOGON32_PROVIDER_DEFAULT, ref handle)) { throw new LogonException( "User logon failed. GetLastWin32Error Number: " + Marshal.GetLastWin32Error()); } // ---------------------------------- var dupHandle = IntPtr.Zero; if (!DuplicateToken(handle, SecurityImpersonation, ref dupHandle)) { throw new LogonException( "Logon failed attemting to duplicate handle"); } // Logon Succeeded ! return new WindowsIdentity instance return(new WindowsIdentity(handle)); } // close the open handle to the authenticated account finally { CloseHandle(handle); } }
public void Impersonate(ImpersonatorLogonType logonType = ImpersonatorLogonType.InteractiveLogon) { impersonationContext = Logon(logonType).Impersonate(); }