I am trying to write an impersonating Control where our employees can login as a different domainuser within our apps, see my code below (nearly complete copy of MSDN article):
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool LogonUser(
[MarshalAs(UnmanagedType.LPStr)]String lpszUsername,
[MarshalAs(UnmanagedType.LPStr)]String lpszDomain,
[MarshalAs(UnmanagedType.LPStr)]String lpszPassword,
int dwLogonType,
int dwLogonProvider,
out SafeTokenHandle phToken);
public void LoginAs(string domain, string user, string password)
{
SafeTokenHandle safeTokenHandle;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
//Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(user, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle);
//If no succes throw Win32Exception
if (!returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
this.SetCurrentPrincipal(new WindowsPrincipal(
new WindowsIdentity(safeTokenHandle.DangerousGetHandle())));
}
The SafeTokenHandle
:
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle() : base(true) { }
[DllImport("kernel32.dll", SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
Now I allways get the Win32-Error "Wrong Username or Password". Am I doing something wrong?
Maybe this class will be helpful to you http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User