Question - Can impersonation be used with Forms authentication

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

Applies to

Answer:

Yes, you can either use protocol transition, if you're running on Windows Server 2003, or you can call LogonUser.

If you need to delegate the original caller's identity on machines that are not running Windows Server 2003, or where you cannot use Kerberos authentication, then you need to use the LogonUser API.

To use the LogonUser API

For example :

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?
  }
}

Attributes

  • Author: J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

  • Category: Impersonation and Delegation

  • filePath: ..\Libraries\patterns & practices Library\faq\b0b79bf9-3ac5-4da1-9769-b58393791ccf.xml

  • Pri: 2

  • Rule Type: Implementation

  • Source: patterns & practices Library

  • Status: Release

  • Technology: ASP.NET 2.0

  • Title: Question - Can impersonation be used with Forms authentication

  • Topic: Security

  • Type: Question and Answer

  • ID: b0b79bf9-3ac5-4da1-9769-b58393791ccf