0

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?

Jan P.
  • 3,261
  • 19
  • 26
  • "nearly complete copy of MSDN article" - oh, of course. You wouldn't happen to have a *link* to a particular article would you? There are quite a few of them, and it's possible that we don't know which one you're referring to. – Damien_The_Unbeliever Oct 05 '12 at 06:57
  • Sorry for this, edited my post. – Jan P. Oct 05 '12 at 07:01

2 Answers2

2

Maybe this class will be helpful to you http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

Jack Spektor
  • 1,097
  • 1
  • 11
  • 30
0

You need to specify you user, domain, password before calling method 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); 
фымышонок
  • 1,362
  • 16
  • 22