aspnet2securityfaq0063

Cancel Save Edit
Return to
HomePage
ASPNET2SecurityFAQs


Question: How do I use programmatic impersonation?

Answer:

There are two approaches to using programmatic impersonation in your code and these are based on which form of authentication your ASP.NET application employs. For both cases however, you need to ensure that ASP.NET built-in impersonation is disabled. This, you can specify in the web.config file.
		 <identity impersonate="false">
	
If your ASP.NET web application uses Windows authentication, then to use programmatic impersonation, you need to obtain the WindowsIdentity object from HTTPContext.User. This WindowsIdentity represents the authenticated user. You need then call its Impersonate method as shown below:

		 [WindowsIdentity] winId = [(WindowsIdentity)HttpContext.Current.User.Identity;]
		 [WindowsImpersonationContext] ctx = null;
		 try
		 {
		  // Start impersonating
		  ctx = winId.Impersonate();
		  // Now impersonating
		  // Access resources or perform operation impersonated security context
		 }
		 finally
		 {
		  // Revert impersonation
		  if (ctx != null)
		    ctx.Undo();
		 }
		 // Back to running under the default ASP.NET process identity
	

If your ASP.NET web application uses custom authentication, such as Forms authentication, you must programmatically create a WindowsIdentity object for the caller, which you can then use to impersonate the caller. For this you have two options, depending on your deployment environment
* Use the Win32 LogonUser API (via P/Invoke)
* Use new WindowsIdentity constructor passing in the user principal name (UPN) for the account. This feature is only available in windows server 2003. An example of this is shown below
Important: Your process identity should have TCB permission for using the new WindowsIdentity constructor to get impersonation level token.
Here is sample code for using WindowsIdentity constructor
		 using System.Security.Principal;
		 …. 
		 // Obtain the user Identity token using
		 // [WindowsIdentityConstructor]
		 [WindowsIdentity] winId = new [WindowsIdentity(]
		 userName@fullyqualifieddomainName);
		 [WindowsImpersonationContext] ctx = winId.Impersonate();
		 // Access resources using the identity of the impersonated user 
		 // Revert impersonation
		 ctx.Undo();
	

More information

For more information on using programmatic impersonation, see “How To: Use Impersonation and Delegation in ASP.NET 2.0” at http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000023.asp


Return to
HomePage
ASPNET2SecurityFAQs