WindowsIdentity.Impersonate 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
코드에서 다른 Windows 사용자를 가장할 수 있도록 허용합니다.
오버로드
Impersonate() |
WindowsIdentity 개체가 나타내는 사용자를 가장합니다. |
Impersonate(IntPtr) |
지정된 사용자 토큰이 나타내는 사용자를 가장합니다. |
Impersonate()
WindowsIdentity 개체가 나타내는 사용자를 가장합니다.
public:
virtual System::Security::Principal::WindowsImpersonationContext ^ Impersonate();
public virtual System.Security.Principal.WindowsImpersonationContext Impersonate ();
abstract member Impersonate : unit -> System.Security.Principal.WindowsImpersonationContext
override this.Impersonate : unit -> System.Security.Principal.WindowsImpersonationContext
Public Overridable Function Impersonate () As WindowsImpersonationContext
반환
가장하기 전의 Windows 사용자를 나타내는 개체입니다. 이 개체를 사용하면 원래 사용자의 컨텍스트로 되돌릴 수 있습니다.
예외
익명 ID로 가장하려고 한 경우
Win32 오류가 발생한 경우
예제
다음 예제에서는 관리되지 않는 Win32 LogonUser
함수를 호출하여 Windows 계정 토큰을 가져오는 방법과 해당 토큰을 사용하여 다른 사용자를 가장한 다음 원래 ID로 되돌리는 방법을 보여 줍니다.
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// On Windows Vista and later this sample must be run as an administrator.
#using <System.dll>
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Principal;
using namespace System::Security::Permissions;
[DllImport("advapi32.dll",SetLastError=true)]
bool LogonUser( String^ lpszUsername, String^ lpszDomain, String^ lpszPassword, int dwLogonType, int dwLogonProvider, IntPtr * phToken );
[DllImport("kernel32.dll",CharSet=CharSet::Auto)]
bool CloseHandle( IntPtr handle );
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction::Demand,Name="FullTrust")]
int main()
{
IntPtr tokenHandle = IntPtr(0);
try
{
String^ userName;
String^ domainName;
// 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: " );
domainName = Console::ReadLine();
Console::Write( "Enter the login of a user on {0} that you wish to impersonate: ", domainName );
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;
const int SecurityImpersonation = 2;
tokenHandle = IntPtr::Zero;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser( userName, domainName, Console::ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &tokenHandle );
Console::WriteLine( "LogonUser called." );
if ( false == returnValue )
{
int ret = Marshal::GetLastWin32Error();
Console::WriteLine( "LogonUser failed with error code : {0}", ret );
throw gcnew System::ComponentModel::Win32Exception( ret );
}
Console::WriteLine( "Did LogonUser Succeed? {0}", (returnValue ? (String^)"Yes" : "No") );
Console::WriteLine( "Value of Windows NT token: {0}", tokenHandle );
// Check the identity.
Console::WriteLine( "Before impersonation: {0}", WindowsIdentity::GetCurrent()->Name );
// The token that is passed to the following constructor must
// be a primary token in order to use it for impersonation.
WindowsIdentity^ newId = gcnew WindowsIdentity( tokenHandle );
WindowsImpersonationContext^ impersonatedUser = newId->Impersonate();
// Check the identity.
Console::WriteLine( "After impersonation: {0}", WindowsIdentity::GetCurrent()->Name );
// Stop impersonating the user.
impersonatedUser->Undo();
// Check the identity.
Console::WriteLine( "After Undo: {0}", WindowsIdentity::GetCurrent()->Name );
// Free the tokens.
if ( tokenHandle != IntPtr::Zero )
CloseHandle( tokenHandle );
}
catch ( Exception^ ex )
{
Console::WriteLine( "Exception occurred. {0}", ex->Message );
}
}
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// On Windows Vista and later this sample must be run as an administrator.
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security;
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 SafeTokenHandle phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Main(string[] args)
{
SafeTokenHandle safeTokenHandle;
try
{
string userName, domainName;
// 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: ");
domainName = Console.ReadLine();
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
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.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
using (safeTokenHandle)
{
Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
{
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
}
}
// Releasing the context object stops the impersonation
// Check the identity.
Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred. " + ex.Message);
}
}
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
' This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
' IMPORTANT NOTES:
' This sample requests the user to enter a password on the console screen.
' Because the console window does not support methods allowing the password to be masked,
' it will be visible to anyone viewing the screen.
' On Windows Vista and later this sample must be run as an administrator.
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.Security.Permissions
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.ConstrainedExecution
Imports System.Security
Module Module1
Public Class ImpersonationDemo
'Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
' ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
' ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
' ByRef phToken As IntPtr) As Boolean
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
<Out()> ByRef phToken As SafeTokenHandle) As Boolean
Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
' Test harness.
' If you incorporate this code into a DLL, be sure to demand FullTrust.
<PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
Public Overloads Shared Sub Main(ByVal args() As String)
Dim safeTokenHandle As SafeTokenHandle = Nothing
Dim tokenHandle As New IntPtr(0)
Try
Dim userName, domainName As String
' 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 a domain on which to log on: ")
domainName = Console.ReadLine()
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName)
userName = Console.ReadLine()
Console.Write("Enter the password for {0}: ", userName)
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary token.
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
' Call LogonUser to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(userName, domainName, Console.ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, safeTokenHandle)
Console.WriteLine("LogonUser called.")
If False = returnValue Then
Dim ret As Integer = Marshal.GetLastWin32Error()
Console.WriteLine("LogonUser failed with error code : {0}", ret)
Throw New System.ComponentModel.Win32Exception(ret)
Return
End If
Using safeTokenHandle
Dim success As String
If returnValue Then success = "Yes" Else success = "No"
Console.WriteLine(("Did LogonUser succeed? " + success))
Console.WriteLine(("Value of Windows NT token: " + safeTokenHandle.DangerousGetHandle().ToString()))
' Check the identity.
Console.WriteLine(("Before impersonation: " + WindowsIdentity.GetCurrent().Name))
' Use the token handle returned by LogonUser.
Using newId As New WindowsIdentity(safeTokenHandle.DangerousGetHandle())
Using impersonatedUser As WindowsImpersonationContext = newId.Impersonate()
' Check the identity.
Console.WriteLine(("After impersonation: " + WindowsIdentity.GetCurrent().Name))
' Free the tokens.
End Using
End Using
End Using
Catch ex As Exception
Console.WriteLine(("Exception occurred. " + ex.Message))
End Try
End Sub
End Class
End Module
Public NotInheritable Class SafeTokenHandle
Inherits SafeHandleZeroOrMinusOneIsInvalid
Private Sub New()
MyBase.New(True)
End Sub
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Boolean
<DllImport("kernel32.dll"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SuppressUnmanagedCodeSecurity()> _
Private Shared Function CloseHandle(ByVal handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Protected Overrides Function ReleaseHandle() As Boolean
Return CloseHandle(handle)
End Function 'ReleaseHandle
End Class
설명
Windows NT 플랫폼에서 현재 사용자는 가장을 허용할 수 있는 충분한 권한이 있어야 합니다.
경고
비동기/대기 패턴과 함께 이 메서드를 사용하지 마십시오. 경우에 따라 결과 WindowsImpersonationContext
삭제된 경우에도 가장이 되돌려지지 않아 안정성 문제가 발생할 수 있습니다. 대신 RunImpersonated
를 사용하세요.
호출자 참고
를 사용한 Impersonate()후에는 메서드를 Undo() 호출하여 가장을 종료하는 것이 중요합니다.
적용 대상
Impersonate(IntPtr)
지정된 사용자 토큰이 나타내는 사용자를 가장합니다.
public:
static System::Security::Principal::WindowsImpersonationContext ^ Impersonate(IntPtr userToken);
public static System.Security.Principal.WindowsImpersonationContext Impersonate (IntPtr userToken);
static member Impersonate : nativeint -> System.Security.Principal.WindowsImpersonationContext
Public Shared Function Impersonate (userToken As IntPtr) As WindowsImpersonationContext
매개 변수
- userToken
-
IntPtr
nativeint
Windows 계정 토큰 핸들입니다. 일반적으로 이 토큰은 Windows API LogonUser
함수에 대한 호출 같은 비관리 코드에 대한 호출을 통해 검색할 수 있습니다.
반환
가장하기 전의 Windows 사용자를 나타내는 개체입니다. 이 개체를 사용하면 원래 사용자의 컨텍스트로 되돌릴 수 있습니다.
예외
Windows에서 Windows NT 상태 코드 STATUS_ACCESS_DENIED를 반환했습니다.
사용 가능한 메모리가 부족한 경우
호출자에게 올바른 권한이 없습니다.
예제
다음 예제에서는 관리되지 않는 Win32 LogonUser
함수를 호출하여 Windows 계정 토큰을 가져오는 방법과 해당 토큰을 사용하여 다른 사용자를 가장한 다음 원래 ID로 되돌리는 방법을 보여 줍니다.
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// On Windows Vista and later this sample must be run as an administrator.
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security;
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 SafeTokenHandle phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Main(string[] args)
{
SafeTokenHandle safeTokenHandle;
try
{
string userName, domainName;
// 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: ");
domainName = Console.ReadLine();
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
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.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
using (safeTokenHandle)
{
Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
}
// Releasing the context object stops the impersonation
// Check the identity.
Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred. " + ex.Message);
}
}
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
' This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
' IMPORTANT NOTES:
' This sample requests the user to enter a password on the console screen.
' Because the console window does not support methods allowing the password to be masked,
' it will be visible to anyone viewing the screen.
' On Windows Vista and later this sample must be run as an administrator.
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.Security.Permissions
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.ConstrainedExecution
Imports System.Security
Module Module1
Public Class ImpersonationDemo
'Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
' ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
' ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
' ByRef phToken As IntPtr) As Boolean
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
<Out()> ByRef phToken As SafeTokenHandle) As Boolean
Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
' Test harness.
' If you incorporate this code into a DLL, be sure to demand FullTrust.
<PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
Public Overloads Shared Sub Main(ByVal args() As String)
Dim safeTokenHandle As SafeTokenHandle
Dim tokenHandle As New IntPtr(0)
Try
Dim userName, domainName As String
' 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 a domain on which to log on: ")
domainName = Console.ReadLine()
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName)
userName = Console.ReadLine()
Console.Write("Enter the password for {0}: ", userName)
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary token.
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
' Call LogonUser to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(userName, domainName, Console.ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, safeTokenHandle)
Console.WriteLine("LogonUser called.")
If False = returnValue Then
Dim ret As Integer = Marshal.GetLastWin32Error()
Console.WriteLine("LogonUser failed with error code : {0}", ret)
Throw New System.ComponentModel.Win32Exception(ret)
Return
End If
Using safeTokenHandle
Dim success As String
If returnValue Then success = "Yes" Else success = "No"
Console.WriteLine(("Did LogonUser succeed? " + success))
Console.WriteLine(("Value of Windows NT token: " + safeTokenHandle.DangerousGetHandle().ToString()))
' Check the identity.
Console.WriteLine(("Before impersonation: " + WindowsIdentity.GetCurrent().Name))
' Use the token handle returned by LogonUser.
Using impersonatedUser As WindowsImpersonationContext = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle())
' Check the identity.
Console.WriteLine(("After impersonation: " + WindowsIdentity.GetCurrent().Name))
' Free the tokens.
End Using
End Using
Catch ex As Exception
Console.WriteLine(("Exception occurred. " + ex.Message))
End Try
End Sub
End Class
End Module
Public NotInheritable Class SafeTokenHandle
Inherits SafeHandleZeroOrMinusOneIsInvalid
Private Sub New()
MyBase.New(True)
End Sub
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Boolean
<DllImport("kernel32.dll"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SuppressUnmanagedCodeSecurity()> _
Private Shared Function CloseHandle(ByVal handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Protected Overrides Function ReleaseHandle() As Boolean
Return CloseHandle(handle)
End Function 'ReleaseHandle
End Class
설명
Windows NT 플랫폼에서 현재 사용자는 가장을 허용할 수 있는 충분한 권한이 있어야 합니다.
참고
값이 인 Impersonate(IntPtr) 메서드를 호출하는 userToken
것은 Win32 RevertToSelf
함수를 호출하는 것과 Zero 같습니다. 다른 사용자가 현재 가장 중인 경우 컨트롤은 원래 사용자로 되돌려집니다.
비관리 코드에 대 한 호출에 대 한 자세한 내용은 참조 하세요. 관리 되지 않는 DLL 함수 사용합니다.
경고
비동기/대기 패턴과 함께 이 메서드를 사용하지 마십시오. 경우에 따라 결과 WindowsImpersonationContext
삭제된 경우에도 가장이 되돌려지지 않아 안정성 문제가 발생할 수 있습니다. 대신 RunImpersonated
를 사용하세요.
호출자 참고
를 사용한 Impersonate(IntPtr)후에는 메서드를 Undo() 호출하여 가장을 종료하는 것이 중요합니다.
적용 대상
.NET