Disposable Impersonation

Tags: .NET

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)


  • Whittaker said

    i just didn’t need a kindle at first, conversely when receiving one for christmas i’m utterly converted. It supply genuine advantages over a book, and makes it such a large amount additional convenient. i might undoubtedly advocate this item:

  • Beaudoin said

    Nice post. I discover something much harder on distinct website pages everyday. Most commonly it is stimulating to see content off their writers and employ a tiny something out of their site. I’d would rather use some while using content on my weblog whether you do not mind. Natually I’ll offer a link on your web blog. Thanks for sharing.

Comments have been disabled for this content.