This project is read-only.

How to impersonate and delegate using LogonUser Windows API

J.D. Meier, Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen.

You can use the Win32 LogonUser() API (via P/Invoke) to create impersonation tokens, only when your WCF Service is not trusted for delegation, because this option forces you to store user name and passwords on your WCF Service.

The following code example shows how the LogonUser API is used for impersonation:
using System.Runtime.InteropServices;
// Declare the logon types as constants
const long LOGON32_LOGON_NETWORK = 3;

// Declare the logon providers as constants
const long LOGON32_PROVIDER_DEFAULT = 0;
[DllImport("advapi32.dll",EntryPoint = "LogonUser")]
private static extern bool LogonUser(
           string lpszUsername,
           string lpszDomain,
           string lpszPassword,
           int dwLogonType,
           int dwLogonProvider,
           ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);

private void ImpersonateAndUse(string Username,
                                        string Password,
                                        string Domain)
  IntPtr token = new IntPtr(0);
  token = IntPtr.Zero;
  // Call LogonUser to obtain a handle to an access token.
  bool returnValue = LogonUser(Username, Domain,Password,
                                 ref token);
  if (false == returnValue)
     int ret = Marshal.GetLastWin32Error();
     string strErr = String.Format("LogonUser failed with error code : {0}", ret);
     throw new ApplicationException(strErr, null);
  WindowsIdentity newId = new WindowsIdentity(token);
  WindowsImpersonationContext impersonatedUser = newId.Impersonate();
     // do the operations using original user security context
     // stop impersonating
     CloseHandle(tokenHandle); // From where did this variable "tokenHandle" came from?

Additional Resources

Last edited May 8, 2008 at 5:07 AM by prashantbansode, version 1


No comments yet.