• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

INFO:在ASP.NET应用程序中实现模拟

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

概要

本文介绍了在 ASP.NET 应用程序中实现模拟的不同方式。
更多信息
如果要在 ASP.NET 中的线程上模拟用户,可以根据您的要求使用以下方法之一:
模拟 IIS 验证的帐户或用户
为 ASP.NET 应用程序的所有请求模拟特定用户
在代码中模拟身份验证用户
在代码中模拟特定用户
注意:可以使用以下代码来确定线程作为哪个用户执行:
System.Security.Principal.WindowsIdentity.GetCurrent().Name
				

模拟 IIS 验证的帐户或用户

若要在收到 ASP.NET 应用程序中每个页的每个请求时模拟 Microsoft Internet 信息服务 (IIS) 身份验证用户,必须在此应用程序的 Web.config 文件中包含 <identity> 标记,并将 impersonate 属性设置为 true。例如:
<identity impersonate="true" />
				
返回页首

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

若要为 ASP.NET 应用程序的所有页面上的所有请求模拟特定用户,可以在该应用程序的 Web.config 文件的 <identity> 标记中指定 userNamepassword 属性。例如:
<identity impersonate="true" userName="accountname" password="password" />
				
注意:在线程上模拟特定用户的进程的标识必须具有“作为操作系统的一部分”权限。默认情况下,Aspnet_wp.exe 进程在名为 ASPNET 的计算机帐户下运行。不过,此帐户没有模拟特定用户所需的权限。如果您尝试模拟特定用户,则会出现一条错误信息。

要解决此问题,请使用下列方法之一:
为 ASPNET 帐户(权限最低的帐户)授予“作为操作系统的一部分”权限。

注意:虽然此方法可以解决问题,但 Microsoft 不建议使用此方法。
在 Machine.config 文件的 <processModel> 配置部分中,将运行 Aspnet_wp.exe 进程所使用的帐户更改为 System 帐户。
返回页首

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

若要仅在运行代码特定部分时模拟身份验证用户 (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 J# .NET
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext =
    ((System.Security.Principal.WindowsIdentity)get_User().get_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>
Visual J# .NET
<%@ Page language="VJ#" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Security.Principal" %>
<%@ Import Namespace="System.Runtime.InteropServices" %>

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

WindowsImpersonationContext impersonationContext;

/** @attribute DllImport("advapi32.dll") */
public static native int LogonUserA(String lpszUserName,
	String lpszDomain,
	String lpszPassword,
	int dwLogonType,
	int dwLogonProvider,
	System.IntPtr[] phToken);

/** @attribute DllImport("advapi32.dll",
 CharSet=CharSet.Auto, SetLastError=true) */
public static native int DuplicateToken(System.IntPtr hToken,
	int impersonationLevel,
	System.IntPtr[] hNewToken);

/** @attribute DllImport("kernel32.dll",CharSet=CharSet.Auto) */
public static native  boolean CloseHandle(System.IntPtr[] handle);


/** @attribute DllImport("advapi32.dll",
 	 CharSet=CharSet.Auto,SetLastError=true) */
public static native boolean RevertToSelf();

public void Page_Load(Object s, System.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 boolean impersonateValidUser(String userName, String domain, String password)
{
	WindowsIdentity tempWindowsIdentity;
	System.IntPtr[] token = new System.IntPtr[1];
	System.IntPtr[] tokenDuplicate = new System.IntPtr[1];

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

}

private void undoImpersonation()
{
	impersonationContext.Undo();
}
</script>
				
注意:在线程上模拟特定用户的进程的标识必须具有“作为操作系统的一部分”权限。默认情况下,Aspnet_wp.exe 进程在名为 ASPNET 的计算机帐户下运行。不过,此帐户没有模拟特定用户所需的权限。如果您尝试模拟特定用户,则会出现一条错误信息。

要解决此问题,请使用下列方法之一:
为 ASPNET 帐户授予“作为操作系统的一部分”权限。

在 Machine.config 文件的 <processModel> 配置部分中,将运行 Aspnet_wp.exe 进程所使用的帐户更改为 System 帐户。

原文地址:http://support.microsoft.com/kb/306158/zh-cn


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ASP.Net如何把文件从一台服务器上传到另外一台服务器发布时间:2022-07-10
下一篇:
asp.net中形式的用法发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap