Exemplo n.º 1
0
        /// <summary>
        /// Executes an action while impersonating a user.
        /// </summary>
        /// <param name="credentials"><see cref="ICredentials"/> for the user to use for impersonation.</param>
        /// <param name="netOnly">Whether impersonation should be used for network access only.</param>
        /// <param name="action">The action to execute in the impersonation context.</param>
        public static void RunImpersonated(this ICredentials credentials, bool netOnly, Action action)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            NetworkCredential Credentials = credentials.GetCredential(null, null);

            using SafeAccessTokenHandle Token = new SafeAccessTokenHandle(ImpersonationSettings.LogonUser(Credentials.Domain, Credentials.UserName, Credentials.SecurePassword, netOnly));

            WindowsIdentity.RunImpersonated(Token, action);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Executes an action while impersonating a user.
        /// </summary>
        /// <param name="credentials"><see cref="ICredentials"/> for the user to use for impersonation.</param>
        /// <param name="netOnly">Whether impersonation should be used for network access only.</param>
        /// <param name="action">The action to execute in the impersonation context.</param>
        public static void RunImpersonated(this ICredentials credentials, bool netOnly, Action action)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            NetworkCredential?Credentials = credentials.GetCredential(s_HttpLocalhost, string.Empty);

            if (Credentials == null)
            {
                throw new UnauthorizedAccessException();
            }

            using SafeAccessTokenHandle Token = new SafeAccessTokenHandle(ImpersonationSettings.LogonUser(Credentials.Domain, Credentials.UserName, Credentials.SecurePassword, netOnly));

            WindowsIdentity.RunImpersonated(Token, action);
        }