.Net如何做Impersonate

    技术2022-05-20  53

    源自MSDN

     

            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]         public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,             int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);         [DllImport("kernel32.dll", CharSet = CharSet.Auto)]         public extern static bool CloseHandle(IntPtr handle);         public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid         {             private SafeTokenHandle()                 : base(true)             {             }             [DllImport("kernel32.dll")]             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]             [SuppressUnmanagedCodeSecurity]             [return: MarshalAs(UnmanagedType.Bool)]             private static extern bool CloseHandle(IntPtr handle);             protected override bool ReleaseHandle()             {                 return CloseHandle(handle);             }         }

     

     

    Sample:

     

                SafeTokenHandle safeTokenHandle;             bool returnValue = LogonUser("report.admin", "China", "report.admin", 2, 0, out safeTokenHandle);             if (!returnValue)             {                 throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());             }             using (safeTokenHandle)             {                 WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());                 using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())                 {                     // Check the identity.                     Console.WriteLine("After impersonation: "                         + WindowsIdentity.GetCurrent().Name);                 }             }

     


    最新回复(0)