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

Windows Impersonation using C#

, 29 Apr 2003 CPOL
Rate this:
Please Sign up or sign in to vote.
An article demonstrating how to use Windows impersonation in your C# code



I've been a member of the CodeProject for over 3 years now, and still haven't contributed any articles - until now.

While designing a Windows Forms-based application, to administrate containers in our Active Directory, I needed a way to allow binding to the AD using alternate credentials. Windows impersonation was the answer. This sample app demonstrates how to use unmanaged code by calling LogonUser() contained within the advapi32.dll, and pass a token handle back to your .NET application using WindowsImpersonationContext.

One of the downfalls to the LogonUser()function is that the password get passed in clear-text.

Partial Source Code

using System.Runtime.InteropServices; // DllImport
using System.Security.Principal; // WindowsImpersonationContext
using System.Security.Permissions; // PermissionSetAttribute

public WindowsImpersonationContext 
    ImpersonateUser(string sUsername, string sDomain, string sPassword)
    // initialize tokens
    IntPtr pExistingTokenHandle = new IntPtr(0);
    IntPtr pDuplicateTokenHandle = new IntPtr(0);
    pExistingTokenHandle = IntPtr.Zero;
    pDuplicateTokenHandle = IntPtr.Zero;
    // if domain name was blank, assume local machine
    if (sDomain == "")
        sDomain = System.Environment.MachineName;

        string sResult = null;

        const int LOGON32_PROVIDER_DEFAULT = 0;

        // create token
        const int LOGON32_LOGON_INTERACTIVE = 2;
        //const int SecurityImpersonation = 2;

        // get handle to token
        bool bImpersonated = LogonUser(sUsername, sDomain, sPassword, 
                ref pExistingTokenHandle);

        // did impersonation fail?
        if (false == bImpersonated)
            int nErrorCode = Marshal.GetLastWin32Error();
            sResult = "LogonUser() failed with error code: " + 
                nErrorCode + "\r\n";

            // show the reason why LogonUser failed
            MessageBox.Show(this, sResult, "Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Error);

        // Get identity before impersonation
        sResult += "Before impersonation: " + 
            WindowsIdentity.GetCurrent().Name + "\r\n";

        bool bRetVal = DuplicateToken(pExistingTokenHandle, 
                ref pDuplicateTokenHandle);

        // did DuplicateToken fail?
        if (false == bRetVal)
            int nErrorCode = Marshal.GetLastWin32Error();
            // close existing handle
            sResult += "DuplicateToken() failed with error code: " 
                + nErrorCode + "\r\n";

            // show the reason why DuplicateToken failed
            MessageBox.Show(this, sResult, "Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            return null;
            // create new identity using new primary token
            WindowsIdentity newId = new WindowsIdentity
            WindowsImpersonationContext impersonatedUser = 

            // check the identity after impersonation
            sResult += "After impersonation: " + 
                WindowsIdentity.GetCurrent().Name + "\r\n";
            MessageBox.Show(this, sResult, "Success", 
                MessageBoxButtons.OK, MessageBoxIcon.Information);
            return impersonatedUser;
    catch (Exception ex)
        throw ex;
        // close handle(s)
        if (pExistingTokenHandle != IntPtr.Zero)
        if (pDuplicateTokenHandle != IntPtr.Zero) 

Points of Interest

This code won't work on Windows 98 or ME because they do not utilize user tokens. Code was built and run using Visual Studio.NET 2002 on Windows XP Service Pack 1.

One of the other uses for this code I've found is, for instantiating COM components that must run in an alternate security context to that of the logged-on user.

If anyone has a more secure method of achieving the same thing, please let me know.


  • Version 1.0 - 04.25.03 - First release version


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


About the Author

Marc Merritt
United States United States
I live in southeastern Pennsylvania, USA with my lovely wife and two beautiful daughters. Life is good. My hobbies are motorcycles, motorcycles, and motorcycles.
I run a riders group called Twisties Motorcycle Club. If you're are a rider in the tri-state area, look us up!
Follow on   Twitter

Comments and Discussions

GeneralMy vote of 5 Pinmembersrilekhamenon1-Sep-14 3:25 
QuestionThanks a lot, you saved 2 hrs. PinmemberMember 103845676-Nov-13 9:23 
AnswerRe: Thanks a lot, you saved 2 hrs. PinmemberMarc Merritt12-Nov-13 9:34 
GeneralRe: Thanks a lot, you saved 2 hrs. PinmemberOded Arbel20-Mar-14 4:04 
GeneralRe: Thanks a lot, you saved 2 hrs. PinmemberMarc Merritt20-Mar-14 4:10 
GeneralRe: Thanks a lot, you saved 2 hrs. PinmemberGuss7720-Mar-14 10:47 
Questionsource code help PinmemberPyakaa17-Dec-12 2:43 
GeneralMy vote of 5 Pinmemberkerkenez20005-Apr-12 0:35 
QuestionCall LogonUser PinmemberMember 822764117-Sep-11 14:40 
QuestionPlease I need a Help Pinmemberkaiserssosse11-Aug-11 2:41 
AnswerRe: Please I need a Help Pinmemberdiialer21-Aug-11 8:36 
GeneralRe: Please I need a Help Pinmemberkaiserssosse21-Aug-11 22:03 
GeneralIs Windows Impersionation Thread or Process Level ? PinmemberThomas Haller27-May-11 3:42 
GeneralThanks Pinmemberolivier gg14-Feb-11 9:43 
GeneralWIndows 7 Pinmembermoralam13-Jul-10 8:58 
GeneralRe: WIndows 7 PinmemberMarc Merritt28-Jan-13 6:25 
QuestionCross domain impersonation Pinmemberatulsureka18-Apr-10 3:25 
AnswerRe: Cross domain impersonation Pinmemberdeadwood8827-Sep-10 3:00 
GeneralRe: Cross domain impersonation PinmemberCstruter26-Oct-10 22:38 
GeneralRe: Cross domain impersonation Pinmembersabh2125-Jan-13 2:32 
GeneralCreate a folder on a remote computer PinmemberShlomo6-Jan-10 2:52 
GeneralWindows 2008 server Pinmembersmithafebinkal3-Dec-08 19:45 
GeneralThis process not working with a WPF application!!! PinmemberArshad Kunnath31-Jul-08 2:36 
GeneralRe: This process not working with a WPF application!!! PinmemberMarc Merritt31-Jul-08 3:59 
This was written in 2003 using the 1.0 Framework version. It's no longer necessary to use P/Invoke for impersonation. Take a look at System.Threading.Thread.CurrentPrincipal.
GeneralRe: This process not working with a WPF application!!! PinmemberMatei Focseneanu12-May-10 6:15 
GeneralRe: This process not working with a WPF application!!! PinmemberJason Jakob20-Jun-13 6:09 
QuestionIt may be.... PinmemberWillian.BR15-May-08 9:55 
GeneralWindows CE .net Pinmemberquestions_c1-Oct-07 3:28 
GeneralRe: Windows CE .net PinmemberMarc Merritt1-Oct-07 16:18 
GeneralRe: Windows CE .net PinmemberPram_Singh4120-Jul-09 5:22 
GeneralError Code 1326 [modified] Pinmembercollapo21-Aug-07 1:56 
GeneralRe: Error Code 1326 Pinmembermirh10-Oct-07 2:59 
GeneralRe: Error Code 1326 Pinmembermustiy10-Feb-10 0:17 
GeneralError 1314 Pinmemberm.aldegheri3-Aug-06 7:28 
GeneralRe: Error 1314 Pinmemberm.aldegheri3-Aug-06 23:23 
GeneralRe: Error 1314 PinmemberMunkieFish11-Apr-07 8:49 
AnswerRe: Error 1314 Pinmemberuppals12-Apr-07 14:06 
GeneralHelp needed Windows 2000 SP4 still getting 1314! -- Re: Error 1314 Pinmemberdevvvy21-Feb-08 21:41 
GeneralRe: Help needed Windows 2000 SP4 still getting 1314! -- Re: Error 1314 PinmemberMarc Merritt26-Feb-08 4:02 
Questionhow to use this in case of a local account? Pinmemberyossof elnaggar27-Jun-06 21:29 
AnswerRe: how to use this in case of a local account? Pinmemberhk1112-Jul-07 20:04 
GeneralRe: how to use this in case of a local account? Pinmemberappalanaidu Aug20118-Feb-12 21:54 
GeneralFirst call takes too long Pinmemberschweeneh4-Apr-06 7:04 
GeneralRe: First call takes too long PinmemberMarc Merritt12-Jun-06 3:24 
GeneralA similar article [modified] PinsitebuilderUwe Keim24-Apr-05 0:59 
GeneralRe: A similar article Pinmembercraigg753-Nov-06 6:57 
GeneralRe: A similar article PinsitebuilderUwe Keim3-Nov-06 7:14 
GeneralImpersonation Pinmemberchriskoiak16-Mar-04 6:13 
QuestionRe: Impersonation Pinmembertee_jay10-Apr-06 23:08 
AnswerRe: Impersonation Pinmemberhk1112-Jul-07 20:01 

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
Web02 | 2.8.150327.1 | Last Updated 30 Apr 2003
Article Copyright 2003 by Marc Merritt
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid