Click here to Skip to main content
Click here to Skip to main content

A small C# Class for impersonating a User

By , 11 Apr 2005
 

Introduction

The term "Impersonation" in a programming context refers to a technique that executes the code under another user context than the user who originally started an application, i.e. the user context is temporarily changed once or multiple times during the execution of an application.

The reason for doing this is to perform tasks that the current user context of an application is not allowed to do. Of course you could grant the user executing an application more privileges, but usually this is a bad idea (due to security constraints) or impossible (e.g. if you don't have full administrative access to a machine to do so).

This article presents an easy-to-use class to impersonate a user. While writing this, I found out that Marc Merrit had written an article ("Windows Impersonation using C#") that uses the same Microsoft knowledge base code (from Q306158) that I have used. The code presented in my article differs in the fact that you could use it inside a using-block to safely release resources and that I use slightly more exceptions to report errors. But from a first look, both his and my article do the same job, so it's up to you to decide what to do.

(For the latest changes, please see the History section below).

Background

I wrote the Impersonator class because of a need to write a web page with ASP.NET to make a server reboot. In order to do this, I needed to impersonate the part of my code that does the actual reboot.

The constructor of the class internally calls the Windows function LogonUser through P/Invoke. Please see the MSDN documentation of the function for a full description of all three parameters (username, domain, password) to the constructor.

Please note: The user context that initiates the impersonation (i.e. not the user context to which it is switched to) needs to have the "Act as part of operating system" privilege set.

Using the code

To use the code, you simply construct the Impersonator class and pass the username, the domain and the password to the constructor. If you place an instance of the class inside a using-block, you need no further steps.

The following is a schematic example of how to use the class:

... 
using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
   ...
   
   <code that executes under the new context>
  
   ...
}
  
...

An example project demonstrating the technique is included in the download of this article (please look at the "Program.cs" for the main demonstration source file). Also the complete source code of the class is included inside the source file "Impersonator.cs".

To include the Impersonator class into your project, simply copy and add the source file "Impersonator.cs" to your project, so that it gets compiled with your project.

Conclusion

In this article, I've shown you a small class to quickly and easily impersonate a part of your code to run under another user context. Hopefully you'll find this class useful.

For questions, comments and remarks, please use the commenting section at the bottom of this article.

References

In addition to the links in the article, the following references might be of interest:

  1. Google search for "Windows Impersonation"

History

  • 2005-04-11: Created first version of article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Uwe Keim
Chief Technology Officer Zeta Producer Desktop CMS
Germany Germany
Member
Uwe does programming since 1989 with experiences in Assembler, C++, MFC and lots of web- and database stuff and now uses ASP.NET and C# extensively, too. He has also teached programming to students at the local university.
 
In his free time, he does climbing, running and mountain biking. Recently he became a father of a cute boy.
 
Some cool, free software from us:
 
Free Test Management Software - Intuitive, competitive, Test Plans. Download now!  
Homepage erstellen - Intuitive, very easy to use. Download now!  
Send large Files online for free by Email
Some random fun stuff in German

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: confirmed working on win2008 r2 webmemberanilkuchi1 Nov '11 - 11:37 
Hi
 
when i am using this on my windows server 2008 R2 its giving me the following error
 
Logon failure: the user has not been granted the requested logon type at this computer
 
Can you let me know how you fixed it on your machine,
 
Thanks
 
Naga Aditya
GeneralMy vote of 4memberAth110 Jun '11 - 3:25 
It should be updated for more modern versions of Windows
Generalipersonator ro sqlserver sspi windows autheticationmemberyacov859420 Mar '11 - 1:54 
HI
how to use this code
to use ipersonation to sqlserver from application
besr regards
yacov
GeneralUnknown Username or Bad PasswordmemberSingh Saab10 Nov '10 - 9:27 
I keep getting an error saying "Unknown Username or Bad Password". I am certain that the credentials I am using are correct. I can connect successfully via windows explorer. Please help!
GeneralMy vote of 5memberM Vaqqas26 Sep '10 - 21:23 
Excellent article Uwe keim. It helped me a lot.
 
Mohammad Vaqqas
GeneralWindows 7memberpsyeye21 Sep '10 - 5:35 
Has anyone Impersonating running on a Windows 7 install?
 
If yes, how?
 
regards,
psyeye
QuestionWithout "Act as part of operating system"memberHabib Ahmed29 Aug '10 - 1:24 
[Please note: The user context that initiates the impersonation (i.e. not the user context to which it is switched to) needs to have the "Act as part of operating system" privilege set.]
 
I have a situation, a normal privileged user is logged in and it wants to impersonate another user (to setup the printer settings under the other user context) - Will your code work?
 
World without walls neither need gates nor windows.
GeneralMy vote of 5memberKarsten Otto27 Aug '10 - 7:35 
Genial, simple and 100% working
GeneralThanks a lot ^^memberliani_8428 Jun '10 - 17:20 
Your code really helps me, thank you Smile | :)
QuestionDoes anyone have problems logging back into their machine after using Impersonator?memberdiyrection4 Jun '10 - 1:30 
Hi,
 
Great class! Very useful, thank you for sharing.
 
I have found that if I use this in unit tests, that when I try to log back into my computer which is part of a domain (when not connected to the domain), my regular user account is no longer cached and I need to reconnect up to the domain to login.
 
Does anyone know if there is a way to re-cache or not lose the local cache of my regular user account's credentials when using Impersonator?
 
Thanks,
Jon

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 11 Apr 2005
Article Copyright 2005 by Uwe Keim
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid