如何在 ASP.NET 应用程序中实现模拟用户身份(在ASP.NET中以管理员身份运行网站)...

news/2024/5/20 14:21:25/文章来源:https://blog.csdn.net/weixin_30268071/article/details/98826414

前言

在实际的项目开发中,我们可能会需要调用一些非托管程序,而有些非托管程序需要有更高的身份权限才能正确执行。本文介绍了如何让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.WindowsIdentitycurrentWindowsIdentity = 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 = 2
Dim LOGON32_PROVIDER_DEFAULT As Integer = 0Dim impersonationContext As WindowsImpersonationContextDeclare 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 IntegerDeclare Auto Function DuplicateToken Lib "advapi32.dll" ( _ByVal ExistingTokenHandle As IntPtr, _ByVal ImpersonationLevel As Integer, _ByRef DuplicateTokenHandle As IntPtr) As IntegerDeclare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As LongPublic 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 SubPrivate Function impersonateValidUser(ByVal userName As String, _
ByVal domain As String, ByVal password As String) As BooleanDim tempWindowsIdentity As WindowsIdentityDim token As IntPtr = IntPtr.ZeroDim tokenDuplicate As IntPtr = IntPtr.ZeroimpersonateValidUser = FalseIf RevertToSelf() ThenIf LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 ThenIf DuplicateToken(token, 2, tokenDuplicate) <> 0 ThentempWindowsIdentity = New WindowsIdentity(tokenDuplicate)impersonationContext = tempWindowsIdentity.Impersonate()If Not impersonationContext Is Nothing ThenimpersonateValidUser = TrueEnd IfEnd IfEnd IfEnd IfIf Not tokenDuplicate.Equals(IntPtr.Zero) ThenCloseHandle(tokenDuplicate)End IfIf Not token.Equals(IntPtr.Zero) ThenCloseHandle(token)End If
End FunctionPrivate 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 = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;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) != 0){if(DuplicateToken(token, 2, ref tokenDuplicate) != 0) {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

转载于:https://www.cnblogs.com/Soar1991/p/6022550.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_742328.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

浅谈Web网站的架构演变过程

前言 我们以javaweb为例&#xff0c;来搭建一个简单的电商系统&#xff0c;看看这个系统可以如何一步步演变。该系统具备的功能&#xff1a;用户模块&#xff1a;用户注册和管理商品模块&#xff1a;商品展示和管理交易模块&#xff1a;创建交易和管理阶段一、单机构建网站 网站…

varnish加速web网站

简介 Varnish可以有效降低web服务器的负载&#xff0c;提升访问速度。根据官方的说法&#xff0c;Varnish是一个cache型的HTTP反向代理。 按照HTTP协议的处理过程&#xff0c;web服务器接受请求并且返回处理结果&#xff0c;理想情况下服务器要在不做额外处理的情况下&#xff…

手把手教你从零开始用WordPress建站

最近&#xff0c;很多人来问我&#xff0c;怎么做一个实际项目&#xff1f;其实这个说简单也简单&#xff0c;说复杂也复杂&#xff0c;但是不管怎么样&#xff0c;从今天开始&#xff0c;一步一步的走&#xff0c;你肯定可以做一个属于自己的站点。 之前我也在群里说了&#x…

快盘做网站服务器,快盘云服务器地址

快盘云服务器地址 内容精选换一换在您申请了云耀云服务器后&#xff0c;可以通过管理控制台查看和管理您的云耀云服务器。本节介绍如何查看云耀云服务器的详细配置&#xff0c;包括云耀云服务器名称、镜像信息、系统盘、数据盘、安全组、弹性公网IP等信息。登录管理控制台。单击…

websocket用ip不能访问_为什么直接用IP不能访问知乎的网站,而百度却可以?

打开cmd&#xff0c;输入ping baidu.com&#xff0c;然后把得到的ip地址111.13.101.208输入浏览器的地址栏&#xff0c;可以打开百度。但我重复操作ping zhihu.com&#xff0c;得到ip地址54.223.189.245&#xff0c;输入地址栏&#xff0c;返回的却是405 not allowed。想请教一…

网站模板怎么和虚拟服务器,模板站用虚拟主机还是用服务器

模板站用虚拟主机还是用服务器 内容精选换一换本章指导用户使用华为云市场镜像“PHP运行环境AMH4.2面板PHP CentOS6.8”部署AMH环境。AMH是一套通过Web控制和管理服务器的Linux服务器管理系统以及虚拟主机管理系统。弹性云服务器创建成功后&#xff0c;还需要配置安全组&#x…

aix如何查看日志策略_企业网站排名,SEO诊断,网站日志分析经常忽略的6个细节!...

在做SEO的过程中&#xff0c;我们总是会遇到各种莫名其妙的问题&#xff0c;比如&#xff1a;某一天你的网站突然出现收录缓慢的问题&#xff0c;而平时都是秒收录。 最开始我们在做审查的时候&#xff0c;总是在思考&#xff1a; ①是否搜索引擎算法在调整。 ②是否自己的内容…

pHP分析网站日志,通过用数据挖掘技术来分析Web网站日志?

Web日志挖掘是指采用数据挖掘技术&#xff0c;对站点用户访问Web服务器过程中产生的日志数据进行分析处理&#xff0c;从而发现Web用户的访问模式和兴趣爱好等&#xff0c;这些信息对站点建设潜在有用的可理解的未知信息和知识&#xff0c;用于分析站点的被访问情况&#xff0c…

如何进行web端安全性测试_如何使用LoadRunner进行Web网站性能测试?

loadrunner压力测试原理本质就是在loadrunner上模拟多个用户同时按固定行为访问web站点。其中固定行为在loadrunner中是通过录制脚本定义的&#xff0c;多个用户同时访问的策略是在loadrunner的场景中定义的loadrunner压测思路通过loadrunner进行压力测试web应用的主要思路分两…

一个好用的在线微信二维码设计网站

帮一个朋友设计他的微信公众号二维码&#xff0c;本来打算用ps画图&#xff0c;想到之前公众号配图有在线网站&#xff0c;简单方便&#xff0c;类似于这类的工具应该会有很多&#xff0c;在百度上查找体验了一下&#xff0c;终于找到了一款可以快速设计文章末尾二维码的在线网…

计算机找不到was服务器,win7系统搭建网站提示计算机“.”上没有找到wAs服务的图文步骤?...

win7系统搭建网站提示计算机“.”上没有找到wAs服务的图文步骤??在win7系统中&#xff0c;很多用户都会在电脑中使用iis搭建网站&#xff0c;然而在安装完iis&#xff0c;添加了网站之后&#xff0c;网站图标上有一个红叉&#xff0c;单击右键&#xff0c;启动&#xff0c;会…

seo2 php什么意思,url对seo最友好的是

对于静态网站来说&#xff0c;一定程度上来说url可以是每个页面唯一的"身份标志"&#xff0c;对于搜索引擎优化(SEO)来说网站url设置是否合理&#xff0c;页影响着最终的效果&#xff0c;达到事半功倍的效果&#xff0c;今天我根据以往经验来说什么样网站url对于百度…

表格标题浮动html,HTML和CSS 入门系列(二):文字、表单、表格、浮动、定位、框架布局、SEO...

一、文字1.1 属性1.2 字体样式&#xff1a;font-family1.3 字体大小&#xff1a;font-size1.4 字体粗细&#xff1a;font-weight1.5 字体风格&#xff1a;font-style1.6 行高&#xff1a;line-height二、表单点击文字自动关联&#xff1a;三、表格四、浮动4.1 清除浮动.d-paren…

php用sublimetext写网站,sublime text3 phpfmt插件使用

sublime text3 phpfmt插件使用通过包安装管理器安装phpfmt插件.在sublime界面按快捷键 ctrlshiftP选择并选择: Install Package等待片刻输入并选择 phpfmt配置 (Windows)打开并编辑配置文件 ( %AppData%\Sublime Text\Packages\phpfmt\phpfmt.sublime-settings )(建议编辑插件的…

Nginx详解反向代理、负载均衡、LNMP架构上线动态网站

转载于:https://www.cnblogs.com/WIU1905/p/11100752.html

更换服务器对SEO不修改内容,六个步骤搞定更换网站服务器对SEO没影响的方法

谢谢非你不爱的文章投稿近期又许多网站站长盆友发帖子资询说要拆换网址的网络服务器了&#xff0c;可是怕操作失误造成 网址被K&#xff0c;由于早已有许多的网站站长盆友来意见反馈&#xff0c;说自身由于换了IP造成 网址被K了。那麼今日百度搜索百度站长工具新手夏令营论坛版…

java分页sql语句_「sql分页」sql语句 实现分页 - seo实验室

sql分页sql语句 实现分页/*分页思想&#xff1a;比如你要每页获取10条记录&#xff0c;当你显示第5页的记录时&#xff0c;也就是选取第40条至50条的记录.首先应该从所有的记录集中选取50条记录&#xff0c;同时进行倒序,再从中选10条&#xff0c;就完成工作了。下面是一个具体…

花瓣网服务器维护一个月,花瓣网维护网站推荐-只需要这一个网站就够了

推荐一款非常实用的设计师导航&#xff0c;可以说是自己目前用过最好用的设计师导航。里面精选推荐了大量优秀网站&#xff0c;包含高清图库、灵感创意、素材资源、摄影美图、教程文章、设计工具、绘画涂鸦、设计社区、字体下载、图标下载、前端学习、等等众多精选优质站点。目…

常州网站服务器_常州专业网站seo优化推广

网站seol31b10优化推广专业常州&#xff0c;SEO排名&#xff0c;它是指搜索引擎优化关键词排名。而影响到seo排名的因素有很多&#xff0c;比如说域名注册的时间&#xff0c;服务器的空间速度和稳定性&#xff0c;或者像是网站整体的结构&#xff0c;网站的内容等等都是影响了s…

ue怎样显示页面标签_网站各页面该如何布局关键词优化提升排名?

在网站优化中&#xff0c;最值得关注的一个事情就是关键词的布局&#xff0c;因为关键词的布局直接影响着网站的排名。那么怎样布局关键词才能提高页面和关键词的相关性&#xff0c;并提高网站排名呢&#xff1f;下面一起来看看。一、利用HTML标签布局关键词众所周知&#xff0…