From e378e1f7e23cace420cda53a5b6698973391c14d Mon Sep 17 00:00:00 2001 From: David Hall Date: Sat, 9 Mar 2019 22:06:51 -0700 Subject: [PATCH] Added Run extension methods for WindowsIdentity to run methods as an impersonated identity on any platform. --- Security/AccountUtils.cs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/Security/AccountUtils.cs b/Security/AccountUtils.cs index 5e0f6fdd..5a1c7fcc 100644 --- a/Security/AccountUtils.cs +++ b/Security/AccountUtils.cs @@ -1,4 +1,5 @@ -using System.Security.Principal; +using System; +using System.Security.Principal; namespace Vanara.Security { @@ -20,6 +21,35 @@ namespace Vanara.Security return false; } + /// Runs the specified function as the impersonated Windows identity. + /// The impersonated identity under which to run the function. + /// The System.Func to run. + public static void Run(this WindowsIdentity identity, Action func) + { + if (identity is null) func(); +#if NET20 || NET35 || NET40 || NET45 + using (new Principal.WindowsImpersonatedIdentity(identity)) + func(); +#else + WindowsIdentity.RunImpersonated(identity.AccessToken, func); +#endif + } + /// Runs the specified function as the impersonated Windows identity. + /// The type of object used by and returned by the function. + /// The impersonated identity under which to run the function. + /// The System.Func to run. + /// The result of the function. + public static T Run(this WindowsIdentity identity, Func func) + { + if (identity is null) return func(); +#if NET20 || NET35 || NET40 || NET45 + using (new Principal.WindowsImpersonatedIdentity(identity)) + return func(); +#else + return WindowsIdentity.RunImpersonated(identity.AccessToken, func); +#endif + } + public static string SidStringFromUserName(string userName) { var acct = new NTAccount(userName);