Home About

September 3rd, 2013

Impersonate another user in C# - 0

Sometimes is useful to switch to another user account, while your program is already executing. In my situation, I needed to build a JSON alternative for the deprecated SOAP layer in MS-SQL server 2012.In previous MS-SQL versions the SOAP server would accept a username and password, and query the database server using those credentials. Based on the permissions set up in the database , users have access to certain procedures, tables and views.

In C# the SqlConnection class uses the current user when building the connection, you are always logged in as the user running the task. Thus this would require building a whole new security layer, on top of an existing one.

The solution comes in the form of Uwe Keim’s Impersonator class.

This class allows you to pass a valid set of Windows credentials to the runtime, changing the login temporarily.

using (new Impersonator(username, WindowsDomain, password))
/* The code in this block is executed using the impersonated credentials */

Calling SqlConnection.Open from within this block allows you to build a connection using the correct privileges. If the credentials are invalid, an exception is thrown which you can then report back.

How does it work ?

The actual implementation is both simple and elegant. LogonUser is used to validate the login, and obtain a login token. This token is duplicated using DuplicateToken to obtain an Impersonation token. Finally, WindowsIdentity is instantiated to switch the actual Identity for the duration of the using clause.

if (LogonUser(
ref token) != 0)
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();

On exiting the using block, the dispose() method undo’s the impersonation and you are back to who you were.

Foto credit: Elvis the King Kitty by Lisa Larson

Be Sociable, Share!

Comments are closed.

Most popular
Recent Comments
  • ARS: great plugin! I love it! but, it will be so nice if you can add attribute ‘title’ as one of...
  • Nelson: Saved me from doing it myself. Good article.
  • andy: i am currently playing taiwanese server wow in 奈辛瓦里(PVP) and i would like to realm transfer to somewhere there...
  • berties: any english speaking playing on a taiwanese server?
  • web application development: has C# search volume really so constant over the years? really surprising.