Click here to Skip to main content
6,305,776 members and growing! (16,730 online)
Email Password   helpLost your password?
Languages » C# » Samples     Intermediate License: The Code Project Open License (CPOL)

A small C# Class for impersonating a User

By Uwe Keim

Introduced a class that simplifies Windows Impersonation in C#.
C#, VC8.0, Windows, .NET 1.1, ASP.NET, WinForms, IIS 5.1, IIS 6, VS.NET2003, Dev
Posted:11 Apr 2005
Views:98,398
Bookmarked:112 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
47 votes for this article.
Popularity: 8.12 Rating: 4.86 out of 5
1 vote, 2.2%
1

2

3
3 votes, 6.7%
4
41 votes, 91.1%
5

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


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 is also teached programming to students at the local university.

In his free time, he does climbing, running and mountain biking. You can watch him most of the day (and probably night) programming.

Some cool, free software from us:

-----

Zeta Test

Zeta Test is an integrated test management environment that enables you to perform black-box tests, white-box tests, regression tests or change management tests of software applications.

Zeta Test helps you to plan, perform, log, monitor and document the tests, and then to evaluate the test results.

Create and manage your test cases and test plans with Zeta Test. Test your software with test scripts that you created with Zeta Test.

Directly download Zeta Test for free!

-----

Zeta Producer Desktop CMS

Intuitive, completely easy-to-use CMS for Windows. Both Freeware version and full version available.

Try out by yourself now! (direct download)

-----

Zeta Uploader

Easily send large files by e-mail. Windows and web client available.

-----
Occupation: Software Developer
Company: zeta software GmbH
Location: Germany Germany

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 94 (Total in Forum: 94) (Refresh)FirstPrevNext
GeneralNice one Pinmemberfluectho4:56 24 Jun '09  
GeneralGreat job PinmemberRichard Hollis12:43 20 Mar '09  
GeneralRe: Great job PinmemberMember 175271812:19 8 Apr '09  
GeneralThis does not seem to work if a Win XP workstation is on a WorkGroup... Pinmemberdanvmn5:44 2 Mar '09  
GeneralThanks Pinmembercarladinmc5:20 26 Feb '09  
GeneralCan I use this C# class in Vb project PinmemberMember 34815906:43 2 Feb '09  
GeneralHow do you use Impersonator without the using clause? Pinmemberdanvmn5:58 23 Jan '09  
GeneralRe: How do you use Impersonator without the using clause? PinsitebuilderUwe Keim6:02 23 Jan '09  
GeneralRe: How do you use Impersonator without the using clause? Pinmemberdanvmn9:20 23 Jan '09  
GeneralRe: How do you use Impersonator without the using clause? Pinmemberdanvmn9:50 23 Jan '09  
GeneralRe: How do you use Impersonator without the using clause? Pinmemberdanvmn6:57 23 Jan '09  
RantSecurity Risk PinmemberRobinVossen21:51 11 Jan '09  
GeneralOpenFileDialog PinmemberRugbyLeague5:54 15 Dec '08  
GeneralWell done!!! Pinmemberuhcl12:20 5 Nov '08  
GeneralNice job PinmemberJugortha8:08 16 Sep '08  
GeneralRe: Nice job PinsitebuilderUwe Keim9:25 16 Sep '08  
GeneralRe: Nice job Pinmemberfiniduck2:32 30 Oct '08  
GeneralExcellent PinmemberRVW7:58 11 Sep '08  
GeneralGreat Job Pinmembernetizenk14:32 27 Aug '08  
GeneralCould not find a part of the path PinmemberRugbyLeague3:35 15 Aug '08  
GeneralRe: Could not find a part of the path Pinmemberfiniduck2:27 30 Oct '08  
GeneralExcellent PinmemberEmad Attia8:04 30 Jul '08  
GeneralDoesn't work on Windows 2000 Pinmemberweitech22:50 12 Jun '08  
GeneralExtended Version PinsitebuilderUwe Keim7:27 22 May '08  
GeneralRe: Extended Version PinsitebuilderUwe Keim7:27 22 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 11 Apr 2005
Editor: Rinish Biju
Copyright 2005 by Uwe Keim
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project