前言

在实际的项目开发中,我们可能会需要调用一些非托管程序,而有些非托管程序需要有更高的身份权限才能正确执行。本文介绍了如何让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> 标记中指定 userNamepassword 属性。例如:

<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中以管理员身份运行网站)的更多相关文章

  1. 【分分钟内搭建一个带用户系统的博客程序(一)用户系统】asp.net core的Identity真香,EF真香!

    不用不知道,一用香到爆. 老哥是个屌丝前端,但也想写点web应用耍一耍.之前弄过了NodeJs,也弄过JAVA,最近由于写游戏的原因用C#,索性上手一波asp.net core. 这篇博客记录的是,如 ...

  2. asp.net访问网络路径方法(模拟用户登录)

    public class IdentityScope : IDisposable { // obtains user token [DllImport("advapi32.dll" ...

  3. IIS下Asp.Net应用程序多进程设置及Session共享

    背景: 目前项目中在单个进程的应用程序经常会遇到w3c.exe崩溃的情况,于是就设想是否可以通过IIS多进程的方案来避免出现该问题. 于是搜了下“怎么实现多进程的方案”,找到了这篇文章:http:// ...

  4. ASP.NET 应用程序(Application)生命周期概述

    原文:ASP.NET 应用程序(Application)生命周期概述 引用MSDN:ASP.NET 应用程序生命周期概述 本 主题概述应用程序生命周期,列出重要的生命周期事件,并描述如何编写适合应用程 ...

  5. 使用IIS应用程序初始化来保持ASP.NET应用程序的活动

    https://weblog.west-wind.com/posts/2013/Oct/02/Use-IIS-Application-Initialization-for-keeping-ASPNET ...

  6. 【转】vc++MCF/C++/C中怎样让应用程序获得或以管理员权限运行 ,ShellExecuteEX编程 --- 获取管理员权限

    ShellExecuteEX编程 --- 获取管理员权限:http://blog.csdn.net/jhui163/article/details/5873027 怎样让你的应用程序获得管理员权限:就 ...

  7. ASP.Net模拟用户 System.Security.Principal

    一.概述 在实际的项目开发中,我们可能会需要调用一些非托管程序,而有些非托管程序需要有更高的身份权限才能正确执行.本文介绍了如何让IIS承载的ASP.NET网站以特定的账户执行,比如Administr ...

  8. 谈 IIS7.5 Asp.Net模拟用户

    IIS  Asp.模拟用户官方的解释是: 如果要在非默认安全上下文中运行 ASP.NET 应用程序,请使用 ASP.NET 模拟身份验证. 如果您对某个 ASP.NET 应用程序启用了模拟,那么该应用 ...

  9. C#程序用Inno Setup打包,以管理员身份运行的处理方法

    一.C#项目端的处理 目标:快捷方式有带盾的标识 在源码的Properties目录中找到 app.manifest,将其中level="asInvoker" 改成 level=&q ...

随机推荐

  1. Oracle同义词和序列

    同义词:是表.索引.视图的模式对象的一个别名,通过模式对象创建同意词,可以隐藏对象的实际名称和 所有者信息,为对象提供一定的安全性,开发应用程序时:应该尽量避免直接使用表,视图 或其他对象,改用对象的 ...

  2. Centos7部署Kubernetes集群(单工作节点)+配置dashboard可视化UI

    目标:docker+kubernetes+cadvosor+dashboard 一:物理硬件 两台虚拟机(centos7):一台做为主节点(master),一台做为工作节点(node) [root@M ...

  3. 高可用Kubernetes集群-10. 部署kube-proxy

    十二.部署kube-proxy 1. 创建kube-proxy证书 1)创建kube-proxy证书签名请求 # kube-proxy提取CN作为客户端的用户名,即system:kube-proxy. ...

  4. Smokeping配置

    参考文档: 官网:http://oss.oetiker.ch/smokeping/ 参考:http://jaminzhang.github.io/monitoring/smokeping-deploy ...

  5. python sys.argv是什么?

    1.sys.argv 是获取运行python文件的时候命令行参数,且以list形式存储参数 2.sys.argv[0] 代表当前module的名字 下面的代码文件是a.py,当我不用IDE工具,只用命 ...

  6. mysql数据库查询

    查询数据指从数据库中获取所需要的数据.查询数据是数据库操作中最常用,也是最重要的操作.用户可以根据自己对数据的需求,使用不同的查询方式.通过不同的查询方式,可以获得不同的数据.MySQL中是使用SEL ...

  7. daterangepicker时间段插件

    1.序言: daterangepicker是Bootstrap的一个时间组件,使用很方便 用于选择日期范围的JavaScript组件. 设计用于Bootstrap CSS框架. 它最初是为了改善报表而 ...

  8. Opendarlight Carbon 安装

    写在前面 目前最轻松的一次安装过程,感谢大翔哥的帮助. 安装过程 1.Zip包下载 找到Opendaylight官网,进入下载界面找到Carbon版本并下载. 2.Zip包解压 把这个zip压缩包解压 ...

  9. Eclipse项目导入到Android Studio中

    背景 最近需要将Eclipse中的android项目导入到Android Studio中!倒腾一番,记录如下! 步骤1 打开Android Studio(下文称AS),选择Import project ...

  10. 《剑指offer》---左旋转字符串与右旋转字符串

    本文算法使用python3实现 1. 问题1 1.1 题目描述:   汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果.对于一个给定的字符序列S, ...