identity与ASP.NET 模拟

默认状况下,ASP.NET应用程序以本机的ASPNET账号运行,该账号属于普通用户组,权限受到必定的限制,以保障ASP.NET应用程序运行的安全。可是有时须要某个ASP.NET应用程序或者程序中的某段代码执行须要特定权限的操做,好比某个文件的存取,这时就须要给该程序或相应的某段代码赋予某个账号的权限以执行该操做,这种方法称之为身份模拟(Impersonation)。 windows

也就是说若是当前IIS的用户在Windows系统中进行某些操做时权限不足,除了能够对IIS用户设置更高的权限外,还能够进行身份模拟,使当前IIS用户具备某个用户的权限。默认状况下模拟的账户是 IIS APPPOOL\DefaultAppPool,固然能够进行额外的设置。api

经过配置文件 安全

<identity impersonate="true" />

若指定模拟某个用户,则设置userName和password的属性值dom

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

另外也能够经过IIS进行设置ide

身份验证进去 spa

设置特定的帐户 code

   

在代码中开启 blog

在代码中使用身份模拟更加灵活,能够在指定的代码段中使用身份模拟,在该代码段以外恢复使用ASPNET本机账号。该方法要求必须使用Windows的认证身份标识。 token

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();

上例中,须要使用Windows身份验证,不然User.Identity不是WindowsIdentity,强制转换会失败而后报错ip

   

模拟指定帐户

 

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);

 

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;
   } 

 

以上代码试过了,鄙人尝试对某个文件设置权限,当前的windows用户能够读写,不知为什么模拟管理员身份时则不可读写。体如今未开始模拟时System.IO.File.Exists返回true,而开了模拟以后就false。

相关文章
相关标签/搜索