Impersonate with username and password?

Royi Namir picture Royi Namir · Oct 10, 2011 · Viewed 26.7k times · Source
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();

 ...
context.Undo();

Where do i declare a administraotr UserName and Passowrd ?

the accessToken param doesn't help me too much...

Do I have to import DLL'S for it ?

Answer

Stefan picture Stefan · Oct 10, 2011

You need to get the user's token. Use the p/invoke LogonUser from the advapi32.dll:

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(
            string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            out IntPtr phToken);

Example:

IntPtr userToken = IntPtr.Zero;

bool success = External.LogonUser(
  "john.doe", 
  "domain.com", 
  "MyPassword", 
  (int) AdvApi32Utility.LogonType.LOGON32_LOGON_INTERACTIVE, //2
  (int) AdvApi32Utility.LogonProvider.LOGON32_PROVIDER_DEFAULT, //0
  out userToken);

if (!success)
{
  throw new SecurityException("Logon user failed");
}

using (WindowsIdentity.Impersonate(userToken))
{
  // do the stuff with john.doe's credentials
}