首页 技术 正文
技术 2022年11月14日
0 收藏 854 点赞 3,219 浏览 1926 个字

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

也就是说如果当前IIS的用户在Windows系统中进行某些操作时权限不足,除了可以对IIS用户设置更高的权限外,还可以进行身份模拟,使当前IIS用户具有某个用户的权限。默认情况下模拟的帐户是 IIS APPPOOL\DefaultAppPool,当然可以进行额外的设置。

通过配置文件

<identity impersonate="true" />

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

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

另外也可以通过IIS进行设置

identity与ASP.NET 模拟

身份验证进去

identity与ASP.NET 模拟

设置特定的账户

identity与ASP.NET 模拟

在代码中开启

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

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,强制转换会失败然后报错

模拟指定账户

public const int LOGON32_LOGON_INTERACTIVE = ;
public const int LOGON32_PROVIDER_DEFAULT = ;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) != )
{
if(DuplicateToken(token, , ref tokenDuplicate) != )
{
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。

上一篇: IOS自动布局
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905