Click here to Skip to main content
15,395,257 members
Articles / Programming Languages / C#
Posted 29 Apr 2003


149 bookmarked

Windows Impersonation using C#

Rate me:
Please Sign up or sign in to vote.
4.77/5 (49 votes)
29 Apr 2003CPOL
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

Christian Merritt
Chief Technology Officer
Australia Australia
Living abroad and loving life.

Comments and Discussions

QuestionMessage Closed Pin
3-Sep-21 2:13
MemberSiL3NC3-SWX3-Sep-21 2:13 
QuestionSame user name before and after impersonation Pin
phoenicyan8-Oct-15 12:39
Memberphoenicyan8-Oct-15 12:39 
AnswerRe: Same user name before and after impersonation Pin
Christian Merritt19-Oct-15 11:30
MemberChristian Merritt19-Oct-15 11:30 
GeneralMy vote of 5 Pin
srilekhamenon1-Sep-14 2:25
professionalsrilekhamenon1-Sep-14 2:25 
QuestionThanks a lot, you saved 2 hrs. Pin
Member 103845676-Nov-13 8:23
MemberMember 103845676-Nov-13 8:23 
AnswerRe: Thanks a lot, you saved 2 hrs. Pin
Christian Merritt12-Nov-13 8:34
MemberChristian Merritt12-Nov-13 8:34 
GeneralRe: Thanks a lot, you saved 2 hrs. Pin
Oded Arbel20-Mar-14 3:04
MemberOded Arbel20-Mar-14 3:04 
GeneralRe: Thanks a lot, you saved 2 hrs. Pin
Christian Merritt20-Mar-14 3:10
MemberChristian Merritt20-Mar-14 3:10 
GeneralRe: Thanks a lot, you saved 2 hrs. Pin
Guss7720-Mar-14 9:47
MemberGuss7720-Mar-14 9:47 
Questionsource code help Pin
Pyakaa17-Dec-12 1:43
MemberPyakaa17-Dec-12 1:43 
GeneralMy vote of 5 Pin
kerkenez20004-Apr-12 23:35
Memberkerkenez20004-Apr-12 23:35 
QuestionCall LogonUser Pin
Member 822764117-Sep-11 13:40
MemberMember 822764117-Sep-11 13:40 
QuestionPlease I need a Help Pin
kaiserssosse11-Aug-11 1:41
Memberkaiserssosse11-Aug-11 1:41 
AnswerRe: Please I need a Help Pin
diialer21-Aug-11 7:36
Memberdiialer21-Aug-11 7:36 
GeneralRe: Please I need a Help Pin
kaiserssosse21-Aug-11 21:03
Memberkaiserssosse21-Aug-11 21:03 
GeneralIs Windows Impersionation Thread or Process Level ? Pin
Thomas Haller27-May-11 2:42
MemberThomas Haller27-May-11 2:42 
GeneralThanks Pin
olivier gg14-Feb-11 8:43
Memberolivier gg14-Feb-11 8:43 
GeneralWIndows 7 Pin
moralam13-Jul-10 7:58
Membermoralam13-Jul-10 7:58 
GeneralRe: WIndows 7 Pin
Christian Merritt28-Jan-13 5:25
MemberChristian Merritt28-Jan-13 5:25 
QuestionCross domain impersonation Pin
atulsureka18-Apr-10 2:25
Memberatulsureka18-Apr-10 2:25 
AnswerRe: Cross domain impersonation Pin
deadwood8827-Sep-10 2:00
Memberdeadwood8827-Sep-10 2:00 
GeneralRe: Cross domain impersonation Pin
Cstruter26-Oct-10 21:38
MemberCstruter26-Oct-10 21:38 
GeneralRe: Cross domain impersonation Pin
sabh2125-Jan-13 1:32
Membersabh2125-Jan-13 1:32 
GeneralCreate a folder on a remote computer Pin
Shlomo6-Jan-10 1:52
MemberShlomo6-Jan-10 1:52 
GeneralWindows 2008 server Pin
smithafebinkal3-Dec-08 18:45
Membersmithafebinkal3-Dec-08 18:45 

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

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