/// <summary> /// Initializes the impersonation context. /// </summary> protected override void InitializeTarget() { if (!RevertToSelf) { _newIdentity = new NewIdentityHandle(UserName, Domain, Password, LogOnType, LogOnProvider, ImpersonationLevel); } base.InitializeTarget(); }
/// <summary> /// Closes the impersonation context. /// </summary> protected override void CloseTarget() { base.CloseTarget(); if (_newIdentity != null) { _newIdentity.Dispose(); _newIdentity = null; } }
internal static void RunImpersonated <T>(NewIdentityHandle newIdentity, Action <T> executeOperation, T state) { #if NETSTANDARD WindowsIdentity.RunImpersonated(newIdentity?.Handle ?? Microsoft.Win32.SafeHandles.SafeAccessTokenHandle.InvalidHandle, () => executeOperation.Invoke(state)); #else WindowsImpersonationContext context = null; try { context = newIdentity?.Handle.Impersonate() ?? WindowsIdentity.Impersonate(IntPtr.Zero); executeOperation.Invoke(state); } finally { context?.Undo(); } #endif }
private void RunImpersonated <T>(NewIdentityHandle newIdentity, Action <T> executeOperation, T state) { NewIdentityHandle.RunImpersonated(RevertToSelf ? null : newIdentity, executeOperation, state); }