Parker's DevEd Blog

Musings on all software development technologies, and education involving computer science and fraud investigation

Windows Impersonation

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
[
DllImport("kernel32.dll", SetLastError = true)]
[
return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);

public enum LogonType { Interactive = 2, Network = 3, Batch = 4, Service = 5, Unlock = 7, NetworkClearText = 8, NewCredentials = 9 }

public static WindowsImpersonationContext Impersonate(String domain, String user, String password, LogonType type) {
    IntPtr userToken = IntPtr.Zero;
    if(!LogonUser(user, domain, password, (int)type, 0, out userToken))
        throw new Win32Exception(Marshal.GetLastWin32Error());
    try {
        return WindowsIdentity.Impersonate(userToken);
    }
finally {
        CloseHandle(userToken);
    }
}

static void Main(string[] args) {
   
try {
        using(WindowsImpersonationContext wic = Impersonate("DOMAIN", "User.Name", "Password", LogonType.Interactive)) {
            // Do Something as new user
            wic.Undo();
        }
    }
catch(Exception ex) {
        Console.Write(ex.ToString());
    }
finally {
        Console.Read();
    }
}

Comments

No Comments