private static WindowsIdentity LogonUser(string userName, string domainName, string password) { const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; // Call LogonUser to obtain a handle to an access token. IntPtr tokenHandle = IntPtr.Zero; if (!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle)) { NativeError error = NativeError.GetLastError(); throw new Exception("Failed to LogonUser [" + userName + "] in Domain [" + domainName + "]. Error: " + error.ToString()); } const int SecurityImpersonation = 2; IntPtr dupeTokenHandle = IntPtr.Zero; if (!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle)) { NativeError error = NativeError.GetLastError(); if (tokenHandle != IntPtr.Zero) { CloseHandle(tokenHandle); } throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString()); } WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle); // Free the tokens. if (dupeTokenHandle != IntPtr.Zero) { CloseHandle(dupeTokenHandle); } if (tokenHandle != IntPtr.Zero) { CloseHandle(tokenHandle); } return(identity); }
public static NativeError GetError(int number) { return(new NativeError(number, NativeError.GetErrorMessage(number))); }
public static NativeError GetLastError() { int number = Marshal.GetLastWin32Error(); return(new NativeError(number, NativeError.GetErrorMessage(number))); }