Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations
Disposable Impersonation

Impersonating a user in .NET isn't quite as simple as it could be. It's really easy if you you already have a WindowsIdentity or WindowsPrincipal in hand, but to get a handle on an arbitrary user you have to resort to P/Invoking the LogonUser and DuplicateToken APIs to get an impersonation context given only a username and password.

Easy enough to wrap in your own function, if you need to use it, but then you have to remember to Undo() the ImpersonationContext when you're done. Not that bad, but could be neater.

So the solution I came up with today is this:

Create a new class, call it ImpersonationContext, and add our Impersonation code in the constructor - pass the username/password as parameters. The WindowsImpersonationContext object we'll save in a private variable.
Next we'll implement IDisposable in our class and call the WindowsImpersonationContext.Undo() in the Dispose method.

What does this give us? A rather clean and readable way to run a block of code using a different security context, with automatic reversal of the impersonation when we're done.

using (new ImpersonationContext(username, password, domain)
{
      // Run my impersonated code.
}

(Sorry for not bringing actual code - this was written on a closed network so I don't have the sources available)

Published Wednesday, June 30, 2004 10:37 PM by AvnerK

Filed under:

Comments

# Double Hop and ASP.NET - a workaround.@ Wednesday, September 22, 2004 7:18 AM

TrackBack

# Double Hop and ASP.NET - a workaround.@ Wednesday, September 22, 2004 7:39 AM

TrackBack

Leave a Comment

(required) 
(required) 
(optional)
(required)