如何在 ASP.NET 应用程序中实现模拟用户身份(在ASP.NET中以管理员身份运行网站)
前言
在实际的项目开发中,我们可能会需要调用一些非托管程序,而有些非托管程序需要有更高的身份权限才能正确执行。本文介绍了如何让IIS承载的ASP.NET网站以特定的账户执行,比如Administrator。
概要
本文介绍了在 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> 标记中指定 userName 和 password 属性。例如:
<identity impersonate="true" userName="accountname" password="password" />
在代码中模拟身份验证用户
若要仅在运行代码的特定部分时模拟身份验证用户 (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();
在代码中模拟特定用户
若要仅在运行代码的特定部分时模拟特定用户,请使用以下代码:
<%@ 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 =
Dim LOGON32_PROVIDER_DEFAULT As Integer = 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) <> Then
If DuplicateToken(token, , tokenDuplicate) <> 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 Basic .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 = ;
public const int LOGON32_PROVIDER_DEFAULT = ; 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) != )
{
if(DuplicateToken(token, , ref tokenDuplicate) != )
{
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 C# .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>
Visual J# .NET
如何在 ASP.NET 应用程序中实现模拟用户身份(在ASP.NET中以管理员身份运行网站)的更多相关文章
- 【分分钟内搭建一个带用户系统的博客程序(一)用户系统】asp.net core的Identity真香,EF真香!
不用不知道,一用香到爆. 老哥是个屌丝前端,但也想写点web应用耍一耍.之前弄过了NodeJs,也弄过JAVA,最近由于写游戏的原因用C#,索性上手一波asp.net core. 这篇博客记录的是,如 ...
- asp.net访问网络路径方法(模拟用户登录)
public class IdentityScope : IDisposable { // obtains user token [DllImport("advapi32.dll" ...
- IIS下Asp.Net应用程序多进程设置及Session共享
背景: 目前项目中在单个进程的应用程序经常会遇到w3c.exe崩溃的情况,于是就设想是否可以通过IIS多进程的方案来避免出现该问题. 于是搜了下“怎么实现多进程的方案”,找到了这篇文章:http:// ...
- ASP.NET 应用程序(Application)生命周期概述
原文:ASP.NET 应用程序(Application)生命周期概述 引用MSDN:ASP.NET 应用程序生命周期概述 本 主题概述应用程序生命周期,列出重要的生命周期事件,并描述如何编写适合应用程 ...
- 使用IIS应用程序初始化来保持ASP.NET应用程序的活动
https://weblog.west-wind.com/posts/2013/Oct/02/Use-IIS-Application-Initialization-for-keeping-ASPNET ...
- 【转】vc++MCF/C++/C中怎样让应用程序获得或以管理员权限运行 ,ShellExecuteEX编程 --- 获取管理员权限
ShellExecuteEX编程 --- 获取管理员权限:http://blog.csdn.net/jhui163/article/details/5873027 怎样让你的应用程序获得管理员权限:就 ...
- ASP.Net模拟用户 System.Security.Principal
一.概述 在实际的项目开发中,我们可能会需要调用一些非托管程序,而有些非托管程序需要有更高的身份权限才能正确执行.本文介绍了如何让IIS承载的ASP.NET网站以特定的账户执行,比如Administr ...
- 谈 IIS7.5 Asp.Net模拟用户
IIS Asp.模拟用户官方的解释是: 如果要在非默认安全上下文中运行 ASP.NET 应用程序,请使用 ASP.NET 模拟身份验证. 如果您对某个 ASP.NET 应用程序启用了模拟,那么该应用 ...
- C#程序用Inno Setup打包,以管理员身份运行的处理方法
一.C#项目端的处理 目标:快捷方式有带盾的标识 在源码的Properties目录中找到 app.manifest,将其中level="asInvoker" 改成 level=&q ...
随机推荐
- centos下JDK安装及环境变量配置
由于centos安装自带openjdk,需要将其卸载后安装自己的jdk 卸载centos自带jdk 1.查找java :rpm -qa | grep java 2.卸载时提示权限不够,进入root目录 ...
- JY播放器【网易云音乐破解下载】
今天给大家带来一款神器----JY播放器.可以直接下载网易云音乐的歌曲. 目前已经支持平台(蜻蜓FM.喜马拉雅FM.网易云音乐.QQ音乐) 使用方法: 在电脑打开网易云音乐或者网站找到你要听的歌曲或歌 ...
- File Transfer(并查集)
题目大意:将多个电脑通过网线连接起来,不断查询2台电脑之间是否连通. 问题来源:中国大学mooc 05-树8 File Transfer (25 分) We have a network of com ...
- 从零开始的Python学习Episode 12——迭代器&生成器
生成器 列表生成式 用于快速地生成一个列表 a = [x*x for x in range(1,9)] print(a) #输出[1, 4, 9, 16, 25, 36, 49, 64] 也可以用于生 ...
- New York Comic Con 2013 - 2013年纽约动漫展
New York Comic Con - 2013年纽约动漫展 New York Comic Con is the largest pop culture event on the East Coas ...
- 王者荣耀交流协会 -- 第4次Scrum会议
Scrum master : 王磊 要求1 : 工作照片 照片由高远博同学拍摄 ,王露芝同学(外援)没有参加本次会议. 要求2 : 时间跨度:2017年10月16日 18:00 - 18:44 共计4 ...
- mysql 对表格加索引但原表格有重复数据
1.把表中唯一数据搜索创建临时表,最后代替原先表. create table mmmmmm as SELECT * FROM meriadianannotation GROUP BY SeriesID ...
- 使用JSon实现三级联动
JSon实现三级联动 我觉得我这个方法比较麻烦,但是目前技术还比较弱,所以先做个笔记自己理解.目前没有和后台交互,只是在前台页面实现了 jQuery和JSon数据实现的,代码如下: <!DOCT ...
- 基于DPDK的高效数据包捕获技术分析与应用
被NFV的论文折磨了两天,今天上午看了两篇DPDK的综述. 传统的包捕获机制 1. BPF 两个组成部分:转发部分和过滤部分. 转发部分负责从链路层提取数据包并转发给过滤部分. 过滤部分根据过滤规则, ...
- Java实现的词频统计——功能改进
本次改进是在原有功能需求及代码基础上额外做的修改,保证了原有的基础需求之外添加了新需求的功能. 功能: 1. 小文件输入——从控制台由用户输入到文件中,再对文件进行统计: 2.支持命令行输入英文作品的 ...