/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// Please note that the account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> public WindowsImpersonatedIdentity(string userName, string domainName, string password) { if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(domainName) && string.IsNullOrEmpty(password)) { identity = WindowsIdentity.GetCurrent(); } else { if (NativeMethods.LogonUser(userName, domainName, password, domainName == null ? LOGON_TYPE_NEW_CREDENTIALS : LOGON32_LOGON_INTERACTIVE, domainName == null ? LOGON32_PROVIDER_WINNT50 : LOGON32_PROVIDER_DEFAULT, out token) != 0) { #if NETSTANDARD || NETCOREAPP if (!NativeMethods.ImpersonateLoggedOnUser(token.DangerousGetHandle())) { throw new Win32Exception(); } #else identity = new WindowsIdentity(token.DangerousGetHandle()); impersonationContext = identity.Impersonate(); #endif } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// Please note that the account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> public WindowsImpersonatedIdentity(string userName, string domainName, string password) { NativeMethods.SafeTokenHandle token; if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(domainName) && string.IsNullOrEmpty(password)) { identity = WindowsIdentity.GetCurrent(); } else { if (NativeMethods.LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out token) != 0) { identity = new WindowsIdentity(token.DangerousGetHandle()); impersonationContext = identity.Impersonate(); } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } }