前言

在实际的项目开发中,我们可能会需要调用一些非托管程序,而有些非托管程序需要有更高的身份权限才能正确执行。本文介绍了如何让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. Siki_Unity_2-2_NGUI_UI插件学习(3.6.8版本)(未学)

    Unity 2-2 NGUI UI插件学习(3.6.8版本)(未学)

  2. mongodb windows 4 zip安装

    安装mongoDB目的:学习Express,顺带mongodb. 本文目的: 4.0.2的mongodb在windows7上竟然安装不了. 没办法,用压缩包手动安装吧... 安装环境:win7sp1x ...

  3. 1035 Password (20 分)(字符串)

    注意下单复数 #include<bits/stdc++.h> using namespace std; pair<string,string>pa; int main() { ...

  4. MATLAB 笔记

    MATLAB的学习 Matlab 主要有5大部分构成,分别是MATLAB语言,桌面工具与开发环境,数学函数库 ,图形系统和应用程序接口.以及众多的专业工具.

  5. MSCOCO - COCO API 的安装

    在 Windows 下安装 COCO API 的方法. 使用 pip 命令进行安装: pip install git+https://github.com/philferriere/cocoapi.g ...

  6. linux 下 mysql安装和配置

    最近在学习R语言,看到R与数据库交互这一部分,就自己动手实践了一下,数据库选择的是mysql,主要记录下linux下怎么安装mysql. 网上的很多资料都有相关的文章,这里只是记录下自己安装过程中遇到 ...

  7. Spark Streaming的使用——转载

    转载自   Spark Streaming 使用

  8. Scrum立会报告+燃尽图(Beta阶段第四次)

    此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2386 项目地址:https://coding.net/u/wuyy694 ...

  9. CS小分队第二阶段冲刺站立会议(5月29日)

    昨日成果:昨天在为主界面设计自主添加应用快捷方式功能,连续遇到困难. 遇到的困难:1.string字符串数组无法在单击事件中使用,提示string无法在eventargs中检索,尝试了各种方式都不行 ...

  10. 第一次c++团队合作项目第三篇随笔

    这次终于想出来了上次问题的解决方法,就是用多态的方法,让小兵,建筑和英雄继承于Object类,通过指针能实现信息的传递. 同时我也完善了地图中每个Pane类的信息,包括每个格子的位置信息,state( ...