Home About

September 3rd, 2013

Impersonate another user in C# - 0

kingkitty2
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(
userName,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
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

    Sorry. No data so far.

Recent Comments
  • Juan Romero: Hi there, it’s a neat little class, but I believe you could do the same thing with the WebClient...
  • anthosh: Hey, THank you very much for your tutorial. It was awesome. But i have a problem that i am not able to...
  • bian: how to get passphase if i have encrypt and decrypt string?? Thanks alot
  • Michael: Hi, I really like your post, thanks a lot, it really helped clear up a few things I could not remember how...
  • Bharat Prajapati: i was trying to import keyword dictionary to this plugin which is in csv format, but i get an error...