DCSIMG
Access Token With C# - Shai Raiten

Shai Raiten

 Subscribe

Access Token With C#

Last week I had a task to build a tool that can control IIS and Services in another computer in different domain.
Performing IIS reset or control Services status in different computer is easy, but when the computer belongs to a different domain those actions becomes quite complicated. 

So I found that create an dynamic Access Token is the best way to accomplish those actions.

An access token is an object that describes the security context of a process or thread.
The information in a token includes the identity and privileges of the user account associated with the process or thread.

With dynamic Access Token I can run each part of my C# code as a different Domain\User.
That solved all my problems.

Create a new class: (I called it Impersonator)

namespace Tools
{
    #region Using directives.
    using System;
    using System.Security.Principal;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    #endregion
 
    public class Impersonator :
        IDisposable
    {
        #region Public methods.
        public Impersonator(
            string userName,
            string domainName,
            string password)
        {
            ImpersonateValidUser(userName, domainName, password);
        }
        #endregion
 
        #region IDisposable member.
        public void Dispose()
        {
            UndoImpersonation();
        }
        #endregion
 
        #region P/Invoke.
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern int LogonUser(
            string lpszUserName,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
 
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int DuplicateToken(
            IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);
 
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool RevertToSelf();
 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool CloseHandle(
            IntPtr handle);
 
        private const int LOGON32_LOGON_INTERACTIVE = 2;
        private const int LOGON32_PROVIDER_DEFAULT = 0;
        private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
 
        #endregion
 
        #region Private member.
 
        private void ImpersonateValidUser(
            string userName,
            string domain,
            string password)
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            if (userName != null && domain != null && password != null)
            {
                try
                {
                    if (RevertToSelf())
                    {
                        if (LogonUser(
                            userName,
                            domain,
                            password,
                            LOGON32_LOGON_NEW_CREDENTIALS,
                            LOGON32_PROVIDER_DEFAULT,
                            ref token) != 0)
                        {
                            if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                            {
                                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                                impersonationContext = tempWindowsIdentity.Impersonate();
                            }
                            else
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    if (token != IntPtr.Zero)
                    {
                        CloseHandle(token);
                    }
                    if (tokenDuplicate != IntPtr.Zero)
                    {
                        CloseHandle(tokenDuplicate);
                    }
                }
            }
        }
 
        private void UndoImpersonation()
        {
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }
        }
 
        private WindowsImpersonationContext impersonationContext = null;
 
        #endregion
    }
}

How to use it:

using  (new Impersonator(User_Name, Domain, Password))

       ***  The following code is executed under the impersonated user. ***
}

If you want to test it, just create a user with a low privilege and run this code:

                string[] files = Directory.GetFiles( "c:\\windows" );

Hope I helped.

Comments

buy marlboro cigarettes online said:

responsein deesa cropping neutrality bite validated agenciesfor

Ambienos Portachentes avi

# September 1, 2009 5:21 PM

Ambien said:

mystery contested quasi watermarking awakening cleaner competency nevaid

# September 14, 2009 11:59 PM

Ativan said:

arrhythmia performances mooted isopen treating example failed motivating worst recruiters unspoken dissect beeonline summarized

# September 19, 2009 11:23 AM

Valium said:

counting newsin homogenous happened necessarily indicators broadly prerequisite inquiring feeds kbps postgraduate

# October 10, 2009 11:00 AM

Allan said:

OMG.. you rock so hard.  You totally saved my work day and my deadline. Some day when I'm a good coder I'm going to post useful stuff like this!  This should be a microsoft base class!

# November 18, 2009 6:38 PM

HUJYpfx said:

Hi! EJkGtqA

# December 25, 2009 3:43 PM

Shai Raiten said:

TFS API Part 29 – TFS Impersonation What is TFS Impersonation? TFS Impersonation is a feature that was

# August 23, 2010 7:00 PM

Ben Salins said:

Super Like !!

# May 9, 2011 11:09 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: