using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; [assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)] [assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")] public class ImpersonationDemo { [DllImport("advapi32.dll", SetLastError=true)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet=CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void Main(string[] args) { IntPtr tokenHandle = new IntPtr(0); //IntPtr dupeTokenHandle = new IntPtr(0); try { string userName, domainName, pass; domainName = "NEMESIS"; userName = "WebAdmin"; pass = "123456"; const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; tokenHandle = IntPtr.Zero; //dupeTokenHandle = IntPtr.Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(userName, domainName, pass, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); if (!returnValue) { int errorCode = 0x5; //ERROR_ACCESS_DENIED throw new System.ComponentModel.Win32Exception(errorCode); } // Check the identity. Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name); // The token that is passed to the following constructor must // be a primary token in order to use it for impersonation. WindowsIdentity newId = new WindowsIdentity(tokenHandle); WindowsImpersonationContext impersonatedUser = newId.Impersonate(); // Check the identity. Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name); // Stop impersonating the user. impersonatedUser.Undo(); // Check the identity. Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name); // Free the tokens. if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle); } catch(Exception ex) { Console.WriteLine("Exception occurred. " + ex.Message); } } }