using System; using System.Runtime.InteropServices; using System.Security.Principal; namespace ArchestrAServices.Common; public class Impersonator : IDisposable { private WindowsImpersonationContext _impersonatedUser; private ArchestraSafeHandle _userHandle; public const int LOGON32_LOGON_INTERACTIVE = 2; public const int LOGON32_LOGON_SERVICE = 3; public const int LOGON32_PROVIDER_DEFAULT = 0; public Impersonator() { } public Impersonator(string userDomain, string userName, string password) { _userHandle = ArchestraSafeHandle.Empty; IntPtr phToken = IntPtr.Zero; if (!LogonUser(userName, userDomain, password, 2, 0, ref phToken)) { throw new ApplicationException("Could not impersonate user"); } _userHandle.Handle = phToken; WindowsIdentity windowsIdentity = new WindowsIdentity(_userHandle.Handle); _impersonatedUser = windowsIdentity.Impersonate(); } public void Dispose() { if (_impersonatedUser != null) { _impersonatedUser.Undo(); if (_userHandle != null && _userHandle.IsInvalid) { _userHandle.Dispose(); } } } [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Auto, 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 static extern bool CloseHandle(IntPtr handle); [DllImport("InteropUtils.dll", CallingConvention = CallingConvention.Cdecl)] public static extern uint GetAdminUserDetails([MarshalAs(UnmanagedType.BStr)] out string pbstrOSDomainName, [MarshalAs(UnmanagedType.BStr)] out string pbstrOSUserName, [MarshalAs(UnmanagedType.BStr)] out string pbstrPassword); }