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

Windows Impersonation using C#

By , 29 Apr 2003
 

Impersonation

Introduction

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;

    try
    {
        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, 
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, 
                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, 
            (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, 
                ref pDuplicateTokenHandle);

        // did DuplicateToken fail?
        if (false == bRetVal)
        {
            int nErrorCode = Marshal.GetLastWin32Error();
            // close existing handle
            CloseHandle(pExistingTokenHandle); 
            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;
        }
        else
        {
            // create new identity using new primary token
            WindowsIdentity newId = new WindowsIdentity
                                        (pDuplicateTokenHandle);
            WindowsImpersonationContext impersonatedUser = 
                                        newId.Impersonate();

            // 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;
    }
    finally
    {
        // close handle(s)
        if (pExistingTokenHandle != IntPtr.Zero)
            CloseHandle(pExistingTokenHandle);
        if (pDuplicateTokenHandle != IntPtr.Zero) 
            CloseHandle(pDuplicateTokenHandle);
    }
}

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.

History

  • Version 1.0 - 04.25.03 - First release version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Marc Merritt
Architect
United States United States
Member
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! http://twistiesmc.com/

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   
QuestionCross domain impersonationmemberatulsureka18 Apr '10 - 2:25 
Hi,
 
I am trying to use this application to impersonate the user across forest. There is no trust between the forests. This code does NOT seem to work in cross forest environment. Is this a known limitation of this app?
 
Atul Sureka
AnswerRe: Cross domain impersonationmemberdeadwood8827 Sep '10 - 2:00 
I'm facing the same problem as well. Any idea how to resolve cross-domain impersonation?
GeneralRe: Cross domain impersonationmemberCstruter26 Oct '10 - 21:38 
This post should give you a clue
http://www.cstruter.com/blog/270[^]
GeneralRe: Cross domain impersonationmembersabh2125 Jan '13 - 1:32 
This code will work only if trust relationship exist between these 2 domains
GeneralCreate a folder on a remote computermemberShlomo6 Jan '10 - 1:52 
Hi,
Thanks for the demo. Wink | ;)
I am trying to create a folder on a remote computer that I know its credentials.
The parent folder is not shared.
So I did what you wrote (with the exception that I used the "SecurityDelegation").
It didn't work. OMG | :OMG:
I don't understand why you do "DuplicateToken" (why can't I use the token that it returned from the LogonUser())?
I also don't understand why when I give the wrong user-name/password I stikk get no error and a valid token.
Please note that when I used anything else than LOGON32_LOGON_NEW_CREDENTIALS I always rectved error 1326. Frown | :(
 
I wrote it in C++ so what I did is
if (!LogonUser(_T("test"),_T("\\\\SHLOMOARAN"),_T("abc"),LOGON32_LOGON_NEW_CREDENTIALS,LOGON32_PROVIDER_DEFAULT,&hToken))
{
// error
}
if (!DuplicateToken(hToken,SecurityDelegation,&hNewToken))
{
// error
}
ImpersonateLoggedOnUser(hNewToken);
if (!hNewToken)
{
// error
}
if (CreateDirectory(path,NULL))
{
// error
}
GeneralWindows 2008 servermembersmithafebinkal3 Dec '08 - 18:45 
Hi Does this code work with windows 2008 server. I am getting command failed error . Can you please help.
 
Thanks,
Smitha.
GeneralThis process not working with a WPF application!!!memberArshad Kunnath31 Jul '08 - 1:36 
I have tried the same process both in forms and WPF applications unfortunately am failed to impersonate user in WPF application.
 
Did i missed anything while impersonating a user in WPF application?
GeneralRe: This process not working with a WPF application!!!memberMarc Merritt31 Jul '08 - 2: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!!!memberMatei Focseneanu12 May '10 - 5:15 
Well I've done a lot of searching about how to use System.Threading.Thread.CurrentPrincipal for impersonation and still haven't found a single place where the process is described.
 
Please help, if you have any clues of how to perform impersonation wihout P/Invoke ...
 
Regards.
QuestionIt may be....memberWillian.BR15 May '08 - 8:55 
Hi,
It's a nice work. Congratulations!
 
But,
 
I would like to run a small windows service application.
It will make some tasks and than the service may run another
process but with other local credentials.
The main service will run under SYSTEM account.
 
Can you help me?
 
Thanks!
 
Willian S. Rodrigues
willian_cpp_br@hotmail.com

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 30 Apr 2003
Article Copyright 2003 by Marc Merritt
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid