在 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 身份验证的帐户或用户

若要模拟 Internet Information Services (IIS) 针对 ASP.NET 应用程序中每个页面的每个请求对用户进行身份验证,必须在此应用程序的 Web.config 文件中包含标记 <identity> ,并将模拟属性设置为 true。 例如:

<identity impersonate="true" />

为 ASP.NET 应用程序的所有请求模拟特定用户

若要为 ASP.NET 应用程序的所有页上的所有请求模拟特定用户,可以在该应用程序的 Web.config 文件的 标记中<identity>指定 userNamepassword 属性。 例如:

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

注意

在线程上模拟特定用户的进程的标识必须具有 Act 作为操作系统权限的一部分 。 默认情况下,Aspnet_wp.exe 进程在名为 ASPNET 的计算机帐户下运行。 但是,此帐户没有模拟特定用户所需的权限。 如果尝试模拟特定用户,则会收到错误消息。 此信息仅适用于 .NET Framework 1.0。 .NET Framework 1.1 不需要此权限。

若要解决此问题,请使用以下方法之一:

  • Act 作为操作系统的一部分 权限授予 ASPNET 帐户 (最低特权帐户) 。

    注意

    尽管可以使用此方法来解决此问题,但 Microsoft 不建议使用此方法。

  • 将运行 Aspnet_wp.exe 进程的帐户更改为 Machine.config 文件的配置部分中的“系统帐户 <processModel> ”。

在代码中模拟进行身份验证的用户

若要仅在运行特定代码部分时模拟身份验证用户 (User.Identity) ,可以使用代码进行跟踪。 此方法要求对用户标识进行身份验证的类型为 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 的计算机上运行,则模拟线程上特定用户的进程的标识必须具有 Act 作为操作系统 特权的一部分。 如果 Aspnet_wp.exe 进程在基于 Windows XP 的计算机或基于 Windows Server 2003 的计算机上运行,则不需要作为操作系统特权的一 部分执行 。 默认情况下,Aspnet_wp.exe 进程在名为 ASPNET 的计算机帐户下运行。 但是,此帐户没有模拟特定用户所需的权限。 如果尝试模拟特定用户,则会收到错误消息。

若要解决此问题,请使用以下方法之一:

  • Act 作为操作系统的一部分 权限授予 ASPNET 帐户。

    注意

    我们不建议使用此方法来解决此问题。

  • 将运行 Aspnet_wp.exe 进程的帐户更改为 Machine.config 文件的配置部分中的“系统帐户 <processModel> ”。

References

ASP.NET 安全性概述