using System; using System.Security; using System.Security.Principal; using System.Threading; using System.Runtime.InteropServices; using System.Text; abstract class Win32Api { [DllImport("Advapi32.dll")] public static extern bool LogonUser( string Username, string Domain, string Password, System.Int32 dwLogonType, System.Int32 dwLogonProvider, ref IntPtr phToken); [DllImport("Advapi32.dll")] public static extern bool GetTokenInformation( IntPtr TokenHandle, int TokenInformationClass, ref int TokenInformation, System.Int32 TokenInformationLength, ref System.Int32 ReturnLength); [DllImport("Kernel32.dll")] public static extern bool CloseHandle( IntPtr hObject); public const int LOGON32_LOGON_NETWORK=3; public const int LOGON32_PROVIDER_DEFAULT=0; public const int TOKEN_TYPE=8; } class Starter { public static void Main() { IntPtr pToken=IntPtr.Zero; bool resp=Win32Api.LogonUser("John", "", "test", Win32Api.LOGON32_LOGON_NETWORK, Win32Api.LOGON32_PROVIDER_DEFAULT, ref pToken); if(resp==false) { Console.WriteLine("Logon to user failed."); return; } int nType=0, bytes=0; string prefix=""; Win32Api.GetTokenInformation(pToken, Win32Api.TOKEN_TYPE, ref nType, 4, ref bytes); if(nType==0) prefix=" not"; Console.WriteLine("John's token is {0} an impersonation token.", prefix); WindowsIdentity newidentity=new WindowsIdentity(pToken); WindowsImpersonationContext wic=newidentity.Impersonate(); // Do something... Console.WriteLine("Doing something for John"); wic.Undo(); Win32Api.CloseHandle(pToken); } }