Click here to Skip to main content
11,637,662 members (73,724 online)
Click here to Skip to main content

A small C# Class for impersonating a User

, 11 Apr 2005 CPOL 696.8K 28K 215
Rate this:
Please Sign up or sign in to vote.
Introduced a class that simplifies Windows Impersonation in C#.

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)

Share

About the Author

Uwe Keim
Chief Technology Officer Zeta Producer Desktop CMS
Germany Germany
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:

German Developer Community  
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
Offline-Homepage-Baukasten

You may also be interested in...

Comments and Discussions

 
QuestionAdding support for local (non-domain) user impersonation Pin
daniel zucker1-Jan-15 7:41
memberdaniel zucker1-Jan-15 7:41 
AnswerRe: Adding support for local (non-domain) user impersonation Pin
Uwe Keim1-Jan-15 7:51
sitebuilderUwe Keim1-Jan-15 7:51 
GeneralRe: Adding support for local (non-domain) user impersonation Pin
Member 117366362-Jun-15 9:25
memberMember 117366362-Jun-15 9:25 
AnswerThank you buddy Pin
aravinth santosh20-Dec-14 9:35
memberaravinth santosh20-Dec-14 9:35 
QuestionThanks! Pin
Emil Ferent18-Nov-14 11:28
memberEmil Ferent18-Nov-14 11:28 
GeneralThank you for posting Pin
Tyler Kalosza25-Jul-14 10:19
memberTyler Kalosza25-Jul-14 10:19 
QuestionGetting “Invalid token for impersonation - it cannot be duplicated” Pin
daniel zucker21-May-14 1:47
memberdaniel zucker21-May-14 1:47 
AnswerRe: Getting “Invalid token for impersonation - it cannot be duplicated” Pin
daniel zucker6-Jul-14 3:07
memberdaniel zucker6-Jul-14 3:07 
QuestionGreat Class - where is the best location for this class? Pin
Member 942814419-May-14 4:49
memberMember 942814419-May-14 4:49 
Bug64 Bit / Desktop Window Manager Pin
Roryap24-Apr-14 3:33
memberRoryap24-Apr-14 3:33 
QuestionThanks!!!! Pin
Member 1068858627-Mar-14 8:09
memberMember 1068858627-Mar-14 8:09 
QuestionThanks!! Pin
Member 867365126-Jan-14 22:55
memberMember 867365126-Jan-14 22:55 
GeneralThanks! Pin
Member 863079324-Jan-14 2:02
memberMember 863079324-Jan-14 2:02 
GeneralThanks Pin
Ankit Mishra9-Jan-14 22:01
memberAnkit Mishra9-Jan-14 22:01 
Questionhi, how can i use this class in workgroup network Pin
mutlu6424-Dec-13 0:56
membermutlu6424-Dec-13 0:56 
Questiongreat job! Pin
barronca9-Nov-13 2:55
memberbarronca9-Nov-13 2:55 
GeneralMy vote of 5 Pin
Gwunhar4-Sep-13 10:17
memberGwunhar4-Sep-13 10:17 
GeneralMy vote of 5 Pin
Menon Santosh8-Aug-13 6:02
professionalMenon Santosh8-Aug-13 6:02 
GeneralMy vote of 5 Pin
SleazyOtto9-Jul-13 10:59
memberSleazyOtto9-Jul-13 10:59 
GeneralMy vote of 5 Pin
VHGN27-Jun-13 21:38
memberVHGN27-Jun-13 21:38 
QuestionThanks Bro! Pin
Duke Ames22-Jun-13 14:57
memberDuke Ames22-Jun-13 14:57 
QuestionWindows Server 2012 Pin
RiqiTang13-May-13 2:06
memberRiqiTang13-May-13 2:06 
GeneralMy vote of 5 Pin
Orcun Iyigun7-Apr-13 21:45
member Orcun Iyigun7-Apr-13 21:45 
GeneralMy vote of 5 Pin
SebastianN_N3-Apr-13 11:26
memberSebastianN_N3-Apr-13 11:26 
QuestionAD Directory catastrophic failure Pin
MacUseless12-Dec-12 2:52
memberMacUseless12-Dec-12 2:52 
GeneralThanks! Pin
sumit ch26-Nov-12 21:45
membersumit ch26-Nov-12 21:45 
Questionnot working for SharePoint 2010 code Pin
abcrahul29-Jun-12 3:12
memberabcrahul29-Jun-12 3:12 
AnswerRe: not working for SharePoint 2010 code Pin
Wayne Dailey13-Sep-12 8:01
memberWayne Dailey13-Sep-12 8:01 
AnswerRe: not working for SharePoint 2010 code Pin
Uwe Keim13-Sep-12 18:10
sitebuilderUwe Keim13-Sep-12 18:10 
SuggestionImproved version without CA warnings and memory leaks Pin
pietvredeveld25-Apr-12 11:06
memberpietvredeveld25-Apr-12 11:06 
GeneralRe: Improved version without CA warnings and memory leaks Pin
Uwe Keim25-Apr-12 12:11
sitebuilderUwe Keim25-Apr-12 12:11 
GeneralRe: Improved version without CA warnings and memory leaks Pin
pietvredeveld26-Apr-12 10:01
memberpietvredeveld26-Apr-12 10:01 
QuestionImpersonator and WebRequest doesn´t work Pin
vicprepr18-Apr-12 4:15
membervicprepr18-Apr-12 4:15 
QuestionNice Pin
opik taufik29-Mar-12 18:06
memberopik taufik29-Mar-12 18:06 
QuestionWorks as expected with ASP.NET MVC3 and .Net 4 in Windows 7 Pin
Reve1018-Mar-12 7:19
memberReve1018-Mar-12 7:19 
Questionbravo Pin
Member 863703210-Feb-12 5:51
memberMember 863703210-Feb-12 5:51 
GeneralMy vote of 5 Pin
Kris Clayton27-Jan-12 0:19
memberKris Clayton27-Jan-12 0:19 
QuestionNot Working in Win Sever 2008 R2 Pin
anilkuchi1-Nov-11 11:39
memberanilkuchi1-Nov-11 11:39 
AnswerRe: Not Working in Win Sever 2008 R2 Pin
chardog3-Dec-11 12:51
memberchardog3-Dec-11 12:51 
GeneralVery Nice & Easy Pin
Srikanth. Vemulapalli16-Oct-11 19:43
memberSrikanth. Vemulapalli16-Oct-11 19:43 
QuestionMy Vote Pin
ahmed farag Ibrahim8-Oct-11 1:43
memberahmed farag Ibrahim8-Oct-11 1:43 
AnswerRe: My Vote Pin
Uwe Keim8-Oct-11 21:40
sitebuilderUwe Keim8-Oct-11 21:40 
GeneralMy vote of 5 Pin
bscaer7-Oct-11 10:11
memberbscaer7-Oct-11 10:11 
QuestionCall LogonUser Pin
Member 822764117-Sep-11 13:38
memberMember 822764117-Sep-11 13:38 
QuestionImpersonating to grant writing files privilege ? Pin
Patrice Dargenton14-Sep-11 3:58
memberPatrice Dargenton14-Sep-11 3:58 
AnswerRe: Impersonating to grant writing files privilege ? Pin
Patrice Dargenton18-Sep-11 21:52
memberPatrice Dargenton18-Sep-11 21:52 
QuestionWorks great for an ASP.Net Web application using IIS and SQl Server Pin
Tarang Deshpande30-Aug-11 11:23
memberTarang Deshpande30-Aug-11 11:23 
I was having all kinds of problems trying to pass client credentials on to IIS which in turn could pass them on to SQL Server. Your class not only worked for me but its implementation and the way to use it in my code is execlent.

Thanks so much.Thumbs Up | :thumbsup:
QuestionDon't working on Windows Server 2008 R2 and Windows 7 ;-( [modified] Pin
tdelgreco22-Aug-11 1:17
membertdelgreco22-Aug-11 1:17 
Generalconfirmed working on win2008 r2 web Pin
xtwinstarx2-Aug-11 16:40
memberxtwinstarx2-Aug-11 16:40 
GeneralRe: confirmed working on win2008 r2 web Pin
Uwe Keim2-Aug-11 19:18
sitebuilderUwe Keim2-Aug-11 19:18 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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