public WindowsImpersonationContext ImpersonateValidUserAndSetThreadPrincipal(string userName, string domain, string password) { WindowsImpersonationContext impersonationContext = null; WindowsIdentity tempWindowsIdentity; var token = IntPtr.Zero; var tokenDuplicate = IntPtr.Zero; IIdentity user; WindowsPrincipal principal; try { if (Convert.ToBoolean(RevertToSelf())) { if (Impersonate.LogonUserA(userName, domain, password, (int)eLogonType.LOGON32_LOGON_INTERACTIVE, (int)eLogonProvider.LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); // apply impersonation to threading user = new WindowsIdentity(token, "NTLM", WindowsAccountType.Normal, true); principal = new WindowsPrincipal((WindowsIdentity)user); Thread.CurrentPrincipal = principal; } } } return(impersonationContext); } catch (Exception ex) { throw ex; } finally { if (!tokenDuplicate.Equals(IntPtr.Zero)) { CloseHandle(tokenDuplicate); } if (!token.Equals(IntPtr.Zero)) { CloseHandle(token); } //return impersonationContext; } }
public bool impersonateValidUser(string userName, string domain, string password) { bool impersonateValidUserRet = false; WindowsIdentity tempWindowsIdentity; var token = IntPtr.Zero; var tokenDuplicate = IntPtr.Zero; impersonateValidUserRet = false; if (Convert.ToBoolean(RevertToSelf())) { if (Impersonate.LogonUserA(userName, domain, password, (int)eLogonType.LOGON32_LOGON_NETWORK, (int)eLogonProvider.LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, (int)eImpersonationLevel.SecurityImpersonation, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext is object) { impersonateValidUserRet = true; } } } } if (!tokenDuplicate.Equals(IntPtr.Zero)) { CloseHandle(tokenDuplicate); } if (!token.Equals(IntPtr.Zero)) { CloseHandle(token); } return(impersonateValidUserRet); }