我正在尝试编写一个模拟控件,我们的员工可以在我们的应用程序中以不同的域用户身份登录,请参见下面的代码(MSDN 文章的几乎完整副本):
[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())));
}
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);
}
}
现在我总是收到 Win32 错误“错误的用户名或密码”。难道我做错了什么?