ASP.NET 애플리케이션에서 가장 구현

이 문서에서는 ASP.NET 애플리케이션에서 가장을 구현하는 다양한 방법을 설명합니다.

원래 제품 버전: ASP.NET
원래 KB 번호: 306158

요약

이 문서에서는 Web.config 파일을 수정하고 특정 코드 섹션을 실행하여 가장을 구현하는 방법을 소개합니다.

다음 Microsoft .NET Framework 클래스 라이브러리 네임스페이스를 참조합니다.

  • System.Web.Security
  • System.Security.Principal
  • System.Runtime.InteropServices

다음 코드를 사용하여 스레드가 실행 중인 사용자를 확인할 수 있습니다.

System.Security.Principal.WindowsIdentity.GetCurrent().Name

IIS 인증된 계정 또는 사용자 가장

ASP.NET 애플리케이션의 모든 페이지에 대한 모든 요청에 대해 사용자를 인증하는 IIS(인터넷 정보 서비스)를 가장하려면 이 애플리케이션의 Web.config 파일에 태그를 포함하고 <identity> 가장 특성을 true로 설정해야 합니다. 예시:

<identity impersonate="true" />

ASP.NET 애플리케이션의 모든 요청에 대해 특정 사용자 가장

ASP.NET 애플리케이션의 모든 페이지에 있는 모든 요청에 대해 특정 사용자를 가장하려면 해당 애플리케이션에 대한 Web.config 파일의 태그에 <identity> 특성과 password 특성을 지정할 userName 수 있습니다. 예시:

<identity impersonate="true" userName="accountname" password="password" />

참고

스레드에서 특정 사용자를 가장하는 프로세스의 ID에는 운영 체제 권한의 일부로 Act가 있어야 합니다. 기본적으로 Aspnet_wp.exe 프로세스는 ASPNET이라는 컴퓨터 계정에서 실행됩니다. 그러나 이 계정에는 특정 사용자를 가장하는 데 필요한 권한이 없습니다. 특정 사용자를 가장하려고 하면 오류 메시지가 표시됩니다. 이 정보는 .NET Framework 1.0에만 적용됩니다. 이 권한은 .NET Framework 1.1에 필요하지 않습니다.

이 문제를 해결하려면 다음 방법 중 하나를 사용합니다.

  • ASPNET 계정(최소 권한 계정)에 운영 체제 권한의 일부로 Act 를 부여합니다.

    참고

    이 메서드를 사용하여 문제를 해결할 수 있지만 이 메서드는 권장하지 않습니다.

  • Aspnet_wp.exe 프로세스가 실행되는 계정을 Machine.config 파일의 구성 섹션에 있는 <processModel> 시스템 계정으로 변경합니다.

코드에서 인증 사용자 가장

특정 코드 섹션을 실행하는 경우에만 인증 사용자(User.Identity)를 가장하려면 코드를 사용하여 따를 수 있습니다. 이 메서드를 사용하려면 인증하는 사용자 ID가 형식 WindowsIdentity입니다.

  • Visual Basic .NET

    Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext
    Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity
    currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity)
    impersonationContext = currentWindowsIdentity.Impersonate()
    'Insert your code that runs under the security context of the authenticating user here.
    impersonationContext.Undo()
    
  • Visual C# .NET

    System.Security.Principal.WindowsImpersonationContext impersonationContext;
    impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
    //Insert your code that runs under the security context of the authenticating user here.
    impersonationContext.Undo();
    

코드에서 특정 사용자 가장

특정 코드 섹션을 실행할 때만 특정 사용자를 가장하려면 다음 코드를 사용합니다.

Visual Basic .NET

<%@ Page Language="VB" %>
<%@ Import Namespace = "System.Web" %>
<%@ Import Namespace = "System.Web.Security" %>
<%@ Import Namespace = "System.Security.Principal" %>
<%@ Import Namespace = "System.Runtime.InteropServices" %>

<script runat=server>
Dim LOGON32_LOGON_INTERACTIVE As Integer = 2
Dim LOGON32_PROVIDER_DEFAULT As Integer = 0
Dim impersonationContext As WindowsImpersonationContext

Declare Function LogonUserA 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 Integer

Declare Auto Function DuplicateToken Lib "advapi32.dll" ( _
                        ByVal ExistingTokenHandle As IntPtr, _
                        ByVal ImpersonationLevel As Integer, _
                        ByRef DuplicateTokenHandle As IntPtr) As Integer

Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long

Public Sub Page_Load(ByVal s As Object, ByVal e As EventArgs)
    If impersonateValidUser("username", "domain", "password") Then
         'Insert your code that runs under the security context of a specific user here.
         undoImpersonation()
    Else
         'Your impersonation failed. Therefore, include a fail-safe mechanism here.
    End If
End Sub

Private Function impersonateValidUser(ByVal userName As String, _
ByVal domain As String, ByVal password As String) As Boolean

    Dim tempWindowsIdentity As WindowsIdentity
    Dim token As IntPtr = IntPtr.Zero
    Dim tokenDuplicate As IntPtr = IntPtr.Zero
    impersonateValidUser = False

    If RevertToSelf() Then
        If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
            If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
                tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
                impersonationContext = tempWindowsIdentity.Impersonate()
                If Not impersonationContext Is Nothing Then
                    impersonateValidUser = True
                End If
            End If
        End If
    End If
    If Not tokenDuplicate.Equals(IntPtr.Zero) Then
        CloseHandle(tokenDuplicate)
    End If
    If Not token.Equals(IntPtr.Zero) Then
        CloseHandle(token)
    End If
End Function

Private Sub undoImpersonation()
    impersonationContext.Undo()
End Sub
</script>

Visual C# .NET

<%@ Page Language="C#"%>
<%@ Import Namespace = "System.Web" %>
<%@ Import Namespace = "System.Web.Security" %>
<%@ Import Namespace = "System.Security.Principal" %>
<%@ Import Namespace = "System.Runtime.InteropServices" %>

<script runat=server>
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

public void Page_Load(Object s, EventArgs e)
{
    if(impersonateValidUser("username", "domain", "password"))
    {
        //Insert your code that runs under the security context of a specific user here.
        undoImpersonation();
    }
    else
    {
        //Your impersonation failed. Therefore, include a fail-safe mechanism here.
    }
}

private bool impersonateValidUser(String userName, String domain, String password)
{
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;

    if(RevertToSelf())
    {
        if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
        LOGON32_PROVIDER_DEFAULT, ref token)!= 0)
        {
            if(DuplicateToken(token, 2, ref tokenDuplicate)!= 0) 
            {
                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                impersonationContext = tempWindowsIdentity.Impersonate();
                if (impersonationContext != null)
                {
                    CloseHandle(token);
                    CloseHandle(tokenDuplicate);
                    return true;
                }
            }
        }
    }
    if(token!= IntPtr.Zero)
        CloseHandle(token);
    if(tokenDuplicate!=IntPtr.Zero)
        CloseHandle(tokenDuplicate);
    return false;
}

private void undoImpersonation()
{
    impersonationContext.Undo();
}
</script>

Aspnet_wp.exe 프로세스가 Windows 2000 기반 컴퓨터에서 실행되는 경우 스레드에서 특정 사용자를 가장하는 프로세스의 ID에는 운영 체제 권한의 일부로 Act 가 있어야 합니다. Aspnet_wp.exe 프로세스가 Windows XP 기반 컴퓨터 또는 Windows Server 2003 기반 컴퓨터에서 실행되는 경우 운영 체제 권한의 일부로 작동 할 필요가 없습니다. 기본적으로 Aspnet_wp.exe 프로세스는 ASPNET이라는 컴퓨터 계정에서 실행됩니다. 그러나 이 계정에는 특정 사용자를 가장하는 데 필요한 권한이 없습니다. 특정 사용자를 가장하려고 하면 오류 메시지가 표시됩니다.

이 문제를 해결하려면 다음 방법 중 하나를 사용합니다.

  • ASPNET 계정에 운영 체제 권한의 일부로 Act 를 부여합니다.

    참고

    이 방법은 문제를 해결하는 데 권장되지 않습니다.

  • Aspnet_wp.exe 프로세스가 실행되는 계정을 Machine.config 파일의 구성 섹션에 있는 <processModel> 시스템 계정으로 변경합니다.

참조

ASP.NET 보안 개요