Beispiel #1
0
        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);
        }
Beispiel #2
0
 /// <summary>
 /// Create a new instance of the <see cref="NativeError" /> class.
 /// </summary>
 /// <param name="number">the error number for the native error</param>
 /// <returns>
 /// An instance of the <see cref="NativeError" /> class for the specified
 /// error number.
 /// </returns>
 /// <remarks>
 /// <para>
 /// The message for the specified error number is lookup up using the
 /// native Win32 <c>FormatMessage</c> function.
 /// </para>
 /// </remarks>
 public static NativeError GetError(int number)
 {
     return(new NativeError(number, NativeError.GetErrorMessage(number)));
 }
Beispiel #3
0
        public static NativeError GetLastError()
        {
            int number = Marshal.GetLastWin32Error();

            return(new NativeError(number, NativeError.GetErrorMessage(number)));
        }