WindowsIdentity.RunImpersonated 方法

定義

多載

RunImpersonated(SafeAccessTokenHandle, Action)

以模擬的 Windows 身分識別執行指定的動作。 您可以使用 RunImpersonated(SafeAccessTokenHandle, Action) 並提供您的函式做為參數,而不需要使用個人化的方法呼叫並在 WindowsImpersonationContext 中執行您的函式。

RunImpersonated<T>(SafeAccessTokenHandle, Func<T>)

以模擬的 Windows 身分識別執行指定的函式。 您可以使用 RunImpersonated(SafeAccessTokenHandle, Action) 並提供您的函式做為參數,而不需要使用個人化的方法呼叫並在 WindowsImpersonationContext 中執行您的函式。

RunImpersonated(SafeAccessTokenHandle, Action)

以模擬的 Windows 身分識別執行指定的動作。 您可以使用 RunImpersonated(SafeAccessTokenHandle, Action) 並提供您的函式做為參數,而不需要使用個人化的方法呼叫並在 WindowsImpersonationContext 中執行您的函式。

public:
 static void RunImpersonated(Microsoft::Win32::SafeHandles::SafeAccessTokenHandle ^ safeAccessTokenHandle, Action ^ action);
public static void RunImpersonated (Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, Action action);
static member RunImpersonated : Microsoft.Win32.SafeHandles.SafeAccessTokenHandle * Action -> unit
Public Shared Sub RunImpersonated (safeAccessTokenHandle As SafeAccessTokenHandle, action As Action)

參數

safeAccessTokenHandle
SafeAccessTokenHandle

模擬之 Windows 身分識別的 SafeAccessTokenHandle。

action
Action

要執行的 System.Action。

範例

下列範例示範如何使用 WindowsIdentity 類別來模擬使用者。

警告

此範例會要求使用者在主控台畫面上輸入密碼。 畫面上會顯示密碼,因為主控台視窗不支援原生遮罩輸入。

// The following example demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTE:
// This sample asks the user to enter a password on the console screen.
// The password will be visible on the screen, because the console window
// does not support masked input natively.

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;

public class ImpersonationDemo
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

    public static void Main()
    {
        // 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.
        Console.Write("Enter the name of the domain on which to log on: ");
        string domainName = Console.ReadLine();

        Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
        string userName = Console.ReadLine();

        Console.Write("Enter the password for {0}: ", userName);

        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.
        SafeAccessTokenHandle safeAccessTokenHandle;
        bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            out safeAccessTokenHandle);

        if (false == returnValue)
        {
            int ret = Marshal.GetLastWin32Error();
            Console.WriteLine("LogonUser failed with error code : {0}", ret);
            throw new System.ComponentModel.Win32Exception(ret);
        }

        Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
        // Check the identity.
        Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);

        // Note: if you want to run as unimpersonated, pass
        //       'SafeAccessTokenHandle.InvalidHandle' instead of variable 'safeAccessTokenHandle'
        WindowsIdentity.RunImpersonated(
            safeAccessTokenHandle,
            // User action
            () =>
            {
                // Check the identity.
                Console.WriteLine("During impersonation: " + WindowsIdentity.GetCurrent().Name);
            }
            );

        // Check the identity again.
        Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
    }
}

備註

注意

這個方法可以可靠地搭配 async/await 模式使用,不同于 Impersonate 。 在非同步方法中,此方法的泛型多載可以與非同步委派引數搭配使用,以便等候產生的工作。

適用於

RunImpersonated<T>(SafeAccessTokenHandle, Func<T>)

以模擬的 Windows 身分識別執行指定的函式。 您可以使用 RunImpersonated(SafeAccessTokenHandle, Action) 並提供您的函式做為參數,而不需要使用個人化的方法呼叫並在 WindowsImpersonationContext 中執行您的函式。

public:
generic <typename T>
 static T RunImpersonated(Microsoft::Win32::SafeHandles::SafeAccessTokenHandle ^ safeAccessTokenHandle, Func<T> ^ func);
public static T RunImpersonated<T> (Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func);
static member RunImpersonated : Microsoft.Win32.SafeHandles.SafeAccessTokenHandle * Func<'T> -> 'T
Public Shared Function RunImpersonated(Of T) (safeAccessTokenHandle As SafeAccessTokenHandle, func As Func(Of T)) As T

類型參數

T

函式使用的物件類型與傳回的物件類型。

參數

safeAccessTokenHandle
SafeAccessTokenHandle

模擬之 Windows 身分識別的 SafeAccessTokenHandle。

func
Func<T>

要執行的 System.Func。

傳回

T

函式的結果。

範例

下列範例示範如何使用 WindowsIdentity 類別來模擬使用者。

警告

此範例會要求使用者在主控台畫面上輸入密碼。 畫面上會顯示密碼,因為主控台視窗不支援原生遮罩輸入。

// The following example demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTE:
// This sample asks the user to enter a password on the console screen.
// The password will be visible on the screen, because the console window
// does not support masked input natively.

using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;

public class ImpersonationDemo
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

    public static void Main()
    {
        // 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.
        Console.Write("Enter the name of the domain on which to log on: ");
        string domainName = Console.ReadLine();

        Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
        string userName = Console.ReadLine();

        Console.Write("Enter the password for {0}: ", userName);

        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.
        SafeAccessTokenHandle safeAccessTokenHandle;
        bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            out safeAccessTokenHandle);

        if (false == returnValue)
        {
            int ret = Marshal.GetLastWin32Error();
            Console.WriteLine("LogonUser failed with error code : {0}", ret);
            throw new System.ComponentModel.Win32Exception(ret);
        }

        Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
        // Check the identity.
        Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);

        // Note: if you want to run as unimpersonated, pass
        //       'SafeAccessTokenHandle.InvalidHandle' instead of variable 'safeAccessTokenHandle'
        WindowsIdentity.RunImpersonated(
            safeAccessTokenHandle,
            // User action
            () =>
            {
                // Check the identity.
                Console.WriteLine("During impersonation: " + WindowsIdentity.GetCurrent().Name);
            }
            );

        // Check the identity again.
        Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
    }
}

備註

注意

這個方法可以可靠地搭配 async/await 模式使用,不同于 Impersonate 。 在非同步方法中,這個方法可以與非同步委派引數搭配使用,以便等候產生的工作。

適用於