/// <summary> /// Gets the user token. /// </summary> /// <param name="userSA">Security Attributes.</param> /// <param name="userToken">User token.</param> public static void GetUserToken(ref Security_attributes userSA, ref IntPtr userToken) { IntPtr Token = new IntPtr(0); IntPtr DupedToken = new IntPtr(0); bool ret; var sa = new Security_attributes(); sa.bInheritHandle = false; sa.Length = Marshal.SizeOf(sa); sa.lpSecurityDescriptor = (IntPtr)0; Token = WindowsIdentity.GetCurrent().Token; const uint GENERIC_ALL = 0x10000000; const int SecurityImpersonation = 2; const int TokenType = 1; ret = DuplicateTokenEx(Token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref DupedToken); if (ret == false) throw new Exception("DuplicateTokenEx failed with " + Marshal.GetLastWin32Error()); userSA = sa; userToken = DupedToken; }
public static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref Security_attributes lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
public static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref Security_attributes lpProcessAttributes, ref Security_attributes lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out Process_Information lpProcessInformation);