Consider LogonUser when you need to impersonate but you don’t have trusted delegation

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

Use the Win32 LogonUser API (via P/Invoke) to create impersonation tokens, only when you don’t have trust for delegation, because this option forces you to store user name and passwords on your WCF Service.
For getting the original users impersonation token, use the basic authentication mode so that you have access to the username and password and then using the LogonUser API – you can get the impersonation token.

For Service accounts you will have to store the username and password securely and then using the LogonUser API – you can get the impersonation token.

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,
                                 (int)LOGON32_LOGON_NETWORK,
                                 (int)LOGON32_PROVIDER_DEFAULT,
                                 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();
  try
  {
     // do the operations using original user security context
  }
  finally
  {
     // stop impersonating
     impersonatedUser.Undo();
     CloseHandle(tokenHandle); // From where did this variable "tokenHandle" came from?
  }
}

Last edited Apr 24, 2008 at 1:05 AM by prashantbansode, version 2

Comments

No comments yet.