コード例 #1
0
    private SafeAccessTokenHandle Logon(ImpersonationSettings settings)
    {
        _logger.LogTrace("Setting up for impersonation");

        // Get the user token for the specified user, domain, and password using the
        // unmanaged LogonUser method.
        // The local machine name can be used for the domain name to impersonate a user on this machine.
        const int LOGON32_PROVIDER_DEFAULT = 0;
        //This parameter causes LogonUser to create a primary token.
        const int LOGON32_LOGON_INTERACTIVE = 2;

        // Call LogonUser to obtain a handle to an access token.
        var returnValue = LogonUser(settings.User, settings.Domain, settings.Password,
                                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                                    out var safeAccessTokenHandle);

        if (!returnValue)
        {
            var ret = Marshal.GetLastWin32Error();
            var exc = new Win32Exception(ret);
            _logger.LogError(exc, "LogonUser failed with error code: {Code}", ret);
            throw exc;
        }

        // Check the identity.
        _logger.LogDebug("Before impersonation: " + WindowsIdentity.GetCurrent().Name);
        return(safeAccessTokenHandle);
    }
コード例 #2
0
    /// <inheritdoc />
    public async Task ExecuteAsync(ImpersonationSettings settings, Func <Task> func)
    {
        var safeAccessTokenHandle = Logon(settings);

        await WindowsIdentity.RunImpersonatedAsync(safeAccessTokenHandle, func);

        _logger.LogDebug("After impersonation: " + WindowsIdentity.GetCurrent().Name);
    }
コード例 #3
0
    /// <inheritdoc />
    public void Execute(ImpersonationSettings settings, Action action)
    {
        var safeAccessTokenHandle = Logon(settings);

        WindowsIdentity.RunImpersonated(safeAccessTokenHandle, action);

        _logger.LogDebug("After impersonation: " + WindowsIdentity.GetCurrent().Name);
    }
コード例 #4
0
    public WindowsImpersonationTests()
    {
        var config = new ConfigurationBuilder()
                     .AddUserSecrets <WindowsImpersonationTests>(true)
                     .Build();

        _settings = new ImpersonationSettings
        {
            User     = config["Username"],
            Password = config["Password"],
            Domain   = config["Domain"]
        };
    }
コード例 #5
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);
        }
コード例 #6
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);
        }
コード例 #7
0
    /// <inheritdoc />
    public async Task <T> ExecuteAsync <T>(ImpersonationSettings settings, Func <Task <T> > func)
    {
        var safeAccessTokenHandle = Logon(settings);

        return(await WindowsIdentity.RunImpersonatedAsync(safeAccessTokenHandle, func));
    }
コード例 #8
0
    /// <inheritdoc />
    public T Execute <T>(ImpersonationSettings settings, Func <T> func)
    {
        var safeAccessTokenHandle = Logon(settings);

        return(WindowsIdentity.RunImpersonated(safeAccessTokenHandle, func));
    }