Share via


WindowsIdentity.RunImpersonated メソッド

定義

オーバーロード

RunImpersonated(SafeAccessTokenHandle, Action)

指定したアクションを、偽装した Windows ID として実行します。 偽装したメソッド呼び出しを使用して WindowsImpersonationContext で関数を実行するのではなく、RunImpersonated(SafeAccessTokenHandle, Action) を使用して関数をパラメーターとして直接指定することができます。

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

指定した関数を、偽装した Windows ID として実行します。 偽装したメソッド呼び出しを使用して WindowsImpersonationContext で関数を実行するのではなく、RunImpersonated(SafeAccessTokenHandle, Action) を使用して関数をパラメーターとして直接指定することができます。

RunImpersonated(SafeAccessTokenHandle, Action)

指定したアクションを、偽装した Windows ID として実行します。 偽装したメソッド呼び出しを使用して WindowsImpersonationContext で関数を実行するのではなく、RunImpersonated(SafeAccessTokenHandle, Action) を使用して関数をパラメーターとして直接指定することができます。

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 ID の 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);
    }
}

注釈

注意

このメソッドは、 とは異なり Impersonate、async/await パターンで確実に使用できます。 非同期メソッドでは、このメソッドのジェネリック オーバーロードを非同期デリゲート引数と共に使用して、結果のタスクを待機できます。

適用対象

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

指定した関数を、偽装した Windows ID として実行します。 偽装したメソッド呼び出しを使用して WindowsImpersonationContext で関数を実行するのではなく、RunImpersonated(SafeAccessTokenHandle, Action) を使用して関数をパラメーターとして直接指定することができます。

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 ID の 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);
    }
}

注釈

注意

このメソッドは、 とは異なり Impersonate、async/await パターンで確実に使用できます。 非同期メソッドでは、このメソッドを非同期デリゲート引数と共に使用して、結果のタスクを待機できます。

適用対象