0

我正在尝试编写一个模拟控件,我们的员工可以在我们的应用程序中以不同的域用户身份登录,请参见下面的代码(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 错误“错误的用户名或密码”。难道我做错了什么?

4

2 回答 2

2

也许这门课会对你有所帮助 http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

于 2012-10-05T07:31:52.163 回答
0

您需要在调用方法 LogonUser 之前指定您的用户、域、密码

string user = "MyUserName" ;
string domain = "MyDomain";
string Password = "MyPassword";

//Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(user, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle); 
于 2015-12-03T17:48:36.933 回答