Click here to Skip to main content
Licence 
First Posted 29 Apr 2003
Views 345,954
Downloads 4,328
Bookmarked 109 times

Windows Impersonation using C#

By Marc Merritt | 29 Apr 2003
An article demonstrating how to use Windows impersonation in your C# code
6 votes, 15.8%
1

2

3
8 votes, 21.1%
4
24 votes, 63.2%
5
4.80/5 - 38 votes
6 removed
μ 4.21, σa 2.56 [?]

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

Technical Lead
Motorcycle Road Racing Forums
United States United States

Member

Follow on Twitter Follow on Twitter
I live in southeastern Pennsylvania, USA with my lovely wife and two beautiful daughters. Life is good. My hobbies are motorcycles, motorcycles, and motorcycles.

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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionCall LogonUser PinmemberMember 822764114:40 17 Sep '11  
QuestionPlease I need a Help Pinmemberkaiserssosse2:41 11 Aug '11  
AnswerRe: Please I need a Help Pinmemberdiialer8:36 21 Aug '11  
GeneralRe: Please I need a Help Pinmemberkaiserssosse22:03 21 Aug '11  
GeneralIs Windows Impersionation Thread or Process Level ? PinmemberThomas Haller3:42 27 May '11  
GeneralThanks Pinmemberolivier gg9:43 14 Feb '11  
GeneralWIndows 7 Pinmembermoralam8:58 13 Jul '10  
QuestionCross domain impersonation Pinmemberatulsureka3:25 18 Apr '10  
AnswerRe: Cross domain impersonation Pinmemberdeadwood883:00 27 Sep '10  
GeneralRe: Cross domain impersonation PinmemberCstruter22:38 26 Oct '10  
GeneralCreate a folder on a remote computer PinmemberShlomo2:52 6 Jan '10  
GeneralWindows 2008 server Pinmembersmithafebinkal19:45 3 Dec '08  
GeneralThis process not working with a WPF application!!! PinmemberArshad Kunnath2:36 31 Jul '08  
GeneralRe: This process not working with a WPF application!!! PinmemberMarc Merritt3:59 31 Jul '08  
GeneralRe: This process not working with a WPF application!!! PinmemberMatei Focseneanu6:15 12 May '10  
QuestionIt may be.... PinmemberWillian.BR9:55 15 May '08  
GeneralWindows CE .net Pinmemberquestions_c3:28 1 Oct '07  
I would like to have this funcionality in an ActiveX running in Windows CE .net
 
Do you know if this is possible?
 
Thanks,
 
Antonio.
 
Antonio
GeneralRe: Windows CE .net PinmemberMarc Merritt16:18 1 Oct '07  
GeneralRe: Windows CE .net PinmemberPram_Singh415:22 20 Jul '09  
GeneralError Code 1326 [modified] Pinmembercollapo1:56 21 Aug '07  
GeneralRe: Error Code 1326 Pinmembermirh2:59 10 Oct '07  
GeneralRe: Error Code 1326 Pinmembermustiy0:17 10 Feb '10  
GeneralError 1314 Pinmemberm.aldegheri7:28 3 Aug '06  
GeneralRe: Error 1314 Pinmemberm.aldegheri23:23 3 Aug '06  
GeneralRe: Error 1314 PinmemberMunkieFish8:49 11 Apr '07  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 30 Apr 2003
Article Copyright 2003 by Marc Merritt
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid