How to perform the Impersonation as a step of Programmatic Impersonation in VB.NET

Configured impersonation, described in the article How to use Configured Impersonation in ASP.NET, allows you to impersonate a user for the entire duration of a request. By using programmatic impersonation (based on the WindowsIdentity.Impersonate() method) , you have more control, such as the ability to impersonate a user for only part of the page request. This method sets up impersonation for a specific account. You identify the account you want to impersonate by using its account token. Account tokens are what Windows uses to track users once their credentials are approved. If you have the token for a user, you can impersonate that user.

The general process is as follows:

1. Obtain an account token for the account you want to impersonate.

2. Use WindowsIdentity.Impersonate() to start impersonation. This method returns a WindowsImpersonationContext object.

3. Call the Undo() method of the WindowsImpersonationContext object to revert to the original identity.

– You can use the instance version, which impersonates the identity represented by the corresponding WindowsIdentity object.

In either case, the Impersonate() method returns a WindowsImpersonationContext object that has a single function—it allows you to revert to the original identity by calling its Undo() method.

The next code lines demonstrate the static version

Dim ImpersonateContext as WindowsImpersonationContext

ImpersonateContext = WindowsIdentity.Impersonate(token)

‘ Now perform tasks under the impersonated ID.

‘ This code will not be able to perform any task that the user would not be allowed to do.)

ImpersonateContext.Undo()

The next paragraphs illustrate the instance version

The ASP.NET provides possibility to determine the identity that your code is currently executing under by calling the WindowsIdentity.GetCurrent() method, at any time. The next function uses this technique to determine the current identity and display the corresponding user name in a label on a web page:

Private Sub DisplayIdentity()

‘ Get the identity under which the code is currently executing.

Dim identity As WindowsIdentity = WindowsIdentity.GetCurrent()

LblInfo.Text += “Executing as: ” + identity.Name + “<br>”

End Sub

You can use the function to create a simple test that impersonates the authenticated IIS identity and then reverts to the standard identity: