private Impersonation(string domain, string username, string password, LogonType logonType) { IntPtr handle; var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle); if (!ok) { var errorCode = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); } var profileInfo = new ProfileInfo(); profileInfo.dwSize = Marshal.SizeOf(profileInfo); profileInfo.lpUserName = username; profileInfo.dwFlags = 1; ok = NativeMethods.LoadUserProfile(handle, ref profileInfo); if (ok == false) { var errorCode = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not load profile. Error code {0}.", errorCode)); } NativeMethods.UnloadUserProfile(handle, profileInfo.hProfile); _handle = new SafeTokenHandle(handle); _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()); }
private Impersonation(string domain, string username, string password, LogonType logonType) { IntPtr handle; var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle); if (!ok) { var errorCode = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); } _handle = new SafeTokenHandle(handle); _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()); }
private void CompleteImpersonation(bool success, IntPtr token, out SafeTokenHandle handle, out WindowsImpersonationContext context) { if (!success) { var errorCode = Marshal.GetLastWin32Error(); if (token != IntPtr.Zero) { NativeMethods.CloseHandle(token); } throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); } handle = new SafeTokenHandle(token); context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()); }
private void CompleteImpersonation(bool success, IntPtr token, out SafeTokenHandle handle, out WindowsImpersonationContext context) { if (!success) { var errorCode = Marshal.GetLastWin32Error(); if (token != IntPtr.Zero) { NativeMethods.CloseHandle(token); } throw new ImpersonationException(new Win32Exception(errorCode)); } handle = new SafeTokenHandle(token); context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()); }