asp.net身份模拟

来源:互联网 发布:淘宝丽得姿海外旗舰店 编辑:程序博客网 时间:2024/04/29 15:52
下面介绍ASP.NET应用程序中使用身份模拟的一个简单应用。例如有一个ASP.NET应用程序要检查服务器端某个文件是否存在,相应的程序代码为:
bool a = File.Exists("D://Share//test.txt");
缺省情况下该ASP.NET应用程序以ASPNET帐号运行。为了安全起见,ASPNET这个帐号并没有服务器端D:/Share/这个目录的访问权限。在不使用身份模拟的情况下,由于ASP.NET应用程序不具有访问该目录的权限,无论文件是否存在,File.Exists的返回值将永远是false。为了解决这个问题,可以另建一个用户帐号:FileExist,并赋予该帐号D:/Share/目录的访问权限。然后在该应用程序的Web.config文件的<identity>标记中指定具体的用户帐号:
<identity impersonate="true" userName="FileExist" password="password" />
模拟IIS认证帐号
这是最简单的一种方法,使用经过IIS认证的帐号执行应用程序。您需要在Web.config文件中添加<identity>标记,并将impersonate属性设置为true:
<identity impersonate="true" />
在这种情况下,用户身份的认证交给IIS来进行。
当允许匿名登录时,IIS将一个匿名登录使用的标识(缺省
情况下是IUSR_MACHINENAME)交给ASP.NET应用程序。当不允许匿名登录时,IIS将认证过的身份标识传递给ASP.NET应用程序。ASP.NET的具体访问权限由该账号的权限决定。
在代码中模拟IIS认证帐号
在代码中使用身份模拟更加灵活,可以在指定的代码段中使用身份模拟,在该代码段之外恢复使用ASPNET本机帐号。该方法要求必须使用Windows的认证身份标识。下面的例子在代码中模拟IIS认证帐号:
Visual Basic .NET
Dim impersonationContext As System.Security.Principal.WindowsImpersonationContextDim currentWindowsIdentity As System.Security.Principal.WindowsIdentitycurrentWindowsIdentity = 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  = 2Dim LOGON32_PROVIDER_DEFAULT As Integer = 0Dim impersonationContext As WindowsImpersonationContextDeclare 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 IntegerDeclare Auto Function DuplicateToken Lib "advapi32.dll"(ByVal ExistingTokenHandle As IntPtr, _                           ImpersonationLevel As Integer, _                           ByRef DuplicateTokenHandle As IntPtr) As IntegerPublic Sub Page_Load(s As Object, 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 IfEnd SubPrivate Function impersonateValidUser(userName As String, _domain As String, password As String) As Boolean    Dim tempWindowsIdentity As WindowsIdentity   Dim token As IntPtr   Dim tokenDuplicate As IntPtr   If LogonUser(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 impersonationContext Is Nothing Then                   impersonateValidUser = False                Else               impersonateValidUser = True                End If      Else        impersonateValidUser = False      End If   Else      impersonateValidUser = False   End IfEnd FunctionPrivate 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", CharSet=CharSet.Auto)]public static extern int LogonUser(String lpszUserName,                                   String lpszDomain,                                  String lpszPassword,                                  int dwLogonType,                                   int dwLogonProvider,                                  ref IntPtr phToken);[DllImport("advapi32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]public extern static int DuplicateToken(IntPtr hToken,                                   int impersonationLevel,                                    ref IntPtr hNewToken);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(LogonUser(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)            return true;         else            return false;       }      else         return false;   }    else      return false;}private void undoImpersonation(){     impersonationContext.Undo();} </script>