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   
Generalconfirmed working on win2008 r2 webmemberxtwinstarx2 Aug '11 - 16:40 
works a treat! thanks a ton!
GeneralRe: confirmed working on win2008 r2 websitebuilderUwe Keim2 Aug '11 - 19:18 
Thanks a lot for your comment, really glad it works with even the latest versions of Windows.
Wollen Sie ganz einfach Ihre eigene Homepage erstellen, ohne HTML-Kenntnisse, einfach, professionell und mit viel Freude? Probieren Sie unser Desktop Content Management System (CMS) Zeta Producer für Windows aus. Komplett mit eigenem Shop, Gästebuch, Weblog, Bildergalerien, Integration von YouTube-Videos. Wir haben eine aktive Anwender-Community, schnellen Support, sympathische Support-Mitarbeiter.

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
AnswerRe: Does anyone have problems logging back into their machine after using Impersonator?memberMember 375330916 Nov '11 - 22:26 
Rather than doing:
 
using(new Impersonator("user", "domain", "pass"))
{
...
}
 
You could try:
 
Impersonator imp = null;
 
try
{
imp = new Impersonator("user", "domain", "pass");
....
}
catch { }
finally
{
if(imp != null)
{
imp.Dispose();
}
}
GeneralMan yo usaved my lifememberhesar5 May '10 - 6:00 
thanks a lot, i still can't understand why AD integration isn't better implemented within .NET
GeneralRe: Man yo usaved my lifemvpUwe Keim5 May '10 - 6:55 
Thank you very much Smile | :)
 
Glad I could help you!
My personal 24/7 webcam
Free Test case management - Intuitive, competitive, Test Plans. Download now!
Free homepage builder - Intuitive, very easy to use. Download now!

GeneralRe: Man yo usaved my lifememberMember 44398461 Jul '11 - 8:51 
You saved my JOB!
GeneralThis 5 year old article is still helping to solve coding problems!memberRCoate19 Apr '10 - 16:31 
Thanks Uwe.
This article and code helped me deliver an application.
I don't know how I would have succeeded without it.
 
I have (of course) given you credit in my code comments.
 
Cheers.
GeneralRe: This 5 year old article is still helping to solve coding problems!mvpUwe Keim19 Apr '10 - 17:41 
Thank you very much! I really like responses like yours Smile | :)
 
Last year, a software development company moved to some of our neighbor offices. Later one developer told me that he thought to know my name from somewhere just to discover that it was from my impersonator class he used in his code, too. Great moment Smile | :)
My personal 24/7 webcam
Free Test case management - Intuitive, competitive, Test Plans. Download now!
Free homepage builder - Intuitive, very easy to use. Download now!

Generalthanksgroupbitayeganeh5 Mar '10 - 21:32 
hello thanks for this useful topics
GeneralThanks Uwe. You realy helped me.memberTamir Nof10 Feb '10 - 3:39 
Smile | :)
GeneralWebsite deployed on https logonuser API stopped working [modified]memberAmit Kumar Thakur13 Dec '09 - 19:17 
Hi,
 
I tried to use the code on my website. When I use it on my machine it works perfect. But as soon as I deploy it on the server which has SSL, it outputs Logon failure: the user has not been granted the requested logon type at this computer. Is this because I'm using ssl or is it because of server configuration. We have windows server 2003.
 
I tried more codes also for impersonation actually. I want to impersonate as a LDAP/local user account to perform directory listing of a remote machine. I am not able to get it done. Do you have any Idea about this please?
 
Can please help? Thanks a lot. Smile | :)
 
Amit Kumar Thakur.
modified on Monday, December 14, 2009 1:51 AM

GeneralNice work, but helpmemberturbohansen21 Aug '09 - 13:10 
I have used your class alot..
 
BUT, now I want to do reach a Computer in another domain!!! with a domain account in the second domain, and there is no trust...
 
I can see that it tries to authenticate me on my own domain, instead of trying the other one!
 
I'am lost.. any idea!? Smile | :)
 
modified on Monday, August 24, 2009 9:48 AM

GeneralRe: Nice work, but helpmemberBit-Smacker17 Sep '09 - 10:00 
turbohansen wrote:
I can see that it tries to authenticate me on my own domain, instead of trying the other one!

 
Have you tried including the domain prefix in the username?
 
ex:
domain\username
GeneralNice onememberfluectho24 Jun '09 - 3:56 
Your artivle is straigth forward, easy to understand an easy to adapt! Thanks a lot for that pice of code!
GeneralGreat jobmemberRichard Hollis20 Mar '09 - 11:43 
A really nice piece of work. Thanks for sharing. I originally went down the Interop route for the MPR stuff (WNetAddConnectionXX etc) but actually impersonation was what I should have used in the first place. This really saved me a lot of time, so thanks again.

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

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