Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >.net下模拟不同身份登陆以获取不同权限

.net下模拟不同身份登陆以获取不同权限

作者头像
阿新
发布于 2018-04-13 02:27:03
发布于 2018-04-13 02:27:03
1.1K00
代码可运行
举报
文章被收录于专栏:c#开发者c#开发者
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
.net下模拟不同身份登陆以获取不同权限  
 
作者:佚名 时间:-- : 出处:互连网 责编:chinaitpower  
 
              摘要:.net下模拟不同身份登陆以获取不同权限 
 
 
不管是asp.net、web service还是window service,程序运行的时候只有本地计算机的部分权限,有时候需要更大的权限,比如读写某台服务器或域中的一台计算机上的文件等,这就需要更大的权限,比如域帐户权限。 

通过获取不同身份的WindowsImpersonationContext对象,可以模拟不同用户登陆,请看我生成的NetworkSecurity类的 
public static WindowsImpersonationContext ImpersonateUser(string strDomain, 
string strLogin, 

string strPwd, 

LogonType logonType, 

LogonProvider logonProvider); 

附NetworkSecurity.cs源代码如下: 

/* 
* Author : TongWei 
* Date : 2005-1-25 
* Rights : China Netwave Inc.@2005 
*/ 

using System; 
using System.Runtime.InteropServices; 
using System.Security.Principal; 
using System.Security.Permissions; 

namespace CNW.OMP.Common.Utility 
{ 
public enum LogonType : int 
{ 
/// <summary> 
/// This logon type is intended for users who will be interactively using the computer, such as a user 
/// being logged on by a terminal server, remote shell, or similar process. This logon type has the 
/// additional expense of caching logon information for disconnected operation, and is therefore 
/// inappropriate for some client/server applications, such as a mail server. 
/// </summary> 
LOGON32_LOGON_INTERACTIVE = , 

/// <summary> 
/// This logon type is intended for high performance servers to authenticate clear text passwords. 
/// The LogonUser function does not cache credentials for this logon type. 
/// </summary> 
LOGON32_LOGON_NETWORK = , 

/// <summary> 
/// This logon type is intended for batch servers, where processes may be executing on behalf of a user 
/// without their direct intervention; or for higher performance servers that process many clear-text 
/// authentication attempts at a time, such as mail or web servers. The LogonUser function does not cache 
/// credentials for this logon type. 
/// </summary> 
LOGON32_LOGON_BATCH = , 

/// <summary> 
/// Indicates a service-type logon. The account provided must have the service privilege enabled. 
/// </summary> 
LOGON32_LOGON_SERVICE = , 

/// <summary> 
/// This logon type is intended for GINA DLLs logging on users who will be interactively using the computer. 
/// This logon type allows a unique audit record to be generated that shows when the workstation was unlocked. 
/// </summary> 
LOGON32_LOGON_UNLOCK = , 

/// <summary> 
/// Windows XP/2000: This logon type preserves the name and password in the authentication packages, 
/// allowing the server to make connections to other network servers while impersonating the client. 
/// This allows a server to accept clear text credentials from a client, call LogonUser, verify that 
/// the user can access the system across the network, and still communicate with other servers. 
/// </summary> 
LOGON32_LOGON_NETWORK_CLEARTEXT = , 

/// <summary> 
/// Windows XP/2000: This logon type allows the caller to clone its current token and specify new credentials 
/// for outbound connections. The new logon session has the same local identity, but uses different credentials 
/// for other network connections. 
/// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider. 
/// </summary> 
LOGON32_LOGON_NEW_CREDENTIALS =  
}; 

public enum LogonProvider : int 
{ 
/// <summary> 
/// Use the standard logon provider for the system. The default security provider is NTLM. 
/// Windows XP: The default provider is negotiate, unless you pass NULL for the domain name and 
/// the user name is not in UPN format. In this case the default provider is NTLM. 
/// </summary> 
LOGON32_PROVIDER_DEFAULT = , 

/// <summary> 
/// Use the Windows NT 3.5 logon provider. 
/// </summary> 
LOGON32_PROVIDER_WINNT35 = , 

/// <summary> 
/// Use the NTLM logon provider. 
/// </summary> 
LOGON32_PROVIDER_WINNT40 = , 

/// <summary> 
/// Windows XP/2000: Use the negotiate logon provider. 
/// </summary> 
LOGON32_PROVIDER_WINNT50 =  
}; 

class SecuUtil32 
{ 
[DllImport("advapi32.dll", SetLastError=true)] 
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, 
int dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle); 

[DllImport("kernel32.dll", CharSet=CharSet.Auto)] 
public extern static bool CloseHandle(IntPtr handle); 

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] 
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, 
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); 
} 

public class NetworkSecurity 
{ 
public NetworkSecurity() 
{ 
// 
// TODO: Add constructor logic here 
// 
} 

/// <summary> 
/// The ImpersonateUser function attempts to log a user on to the local computer. 
/// The local computer is the computer from which ImpersonateUser was called. 
/// You cannot use ImpersonateUser to log on to a remote computer. 
/// You specify the user with a user name and domain, and authenticate the user with a clear-text password. 
/// If the function succeeds, you receive a handle to a token that represents the logged-on user. 
/// You can then use this token handle to impersonate the specified user, or in most cases, 
/// to create a process running in the context of the specified user. 
/// </summary> 
/// <param name="strDomain"> 
/// specifies the name of the domain or server whose account database contains the strLogin account. 
/// </param> 
/// <param name="strLogin">specifies the name of the user.</param> 
/// <param name="strPwd">specifies the clear-text password for the user account specified by strLogin.</param> 
/// <param name="logonType">Specifies the type of logon operation to perform.</param> 
/// <param name="logonProvider">Specifies the logon provider.</param> 
/// <example> 
/// //Add System.Security.dll 
/// //using System.Security.Principal; 
/// 
/// string strDomain=ConfigurationSettings.AppSettings["mSALoginDomainName"]; 
/// string strUser=ConfigurationSettings.AppSettings["mSALoginDomainUser"]; 
/// string strPassword=ConfigurationSettings.AppSettings["mSALoginDomainPassword"]; 
/// 
/// WindowsImpersonationContext impContext = null; 
/// try 
/// { 
/// impContext = NetworkSecurity.ImpersonateUser(strDomain,strUser,strPassword, 
/// LogonType.LOGON32_LOGON_SERVICE, 
/// LogonProvider.LOGON32_PROVIDER_DEFAULT); 
/// } 
/// catch 
/// { 
/// 
/// } 
/// 
/// //work under this logined user 
/// 
/// impContext.Undo(); 
/// </example> 
/// <returns> 
/// </returns> 
public static WindowsImpersonationContext ImpersonateUser(string strDomain, 
string strLogin, 
string strPwd, 
LogonType logonType, 
LogonProvider logonProvider) 
{ 
// Initialize tokens 
IntPtr tokenHandle = new IntPtr(); 
IntPtr dupeTokenHandle = new IntPtr(); 
tokenHandle = IntPtr.Zero; 
dupeTokenHandle = IntPtr.Zero; 

// If domain name was blank, assume local machine 
if (strDomain == "") 
strDomain = System.Environment.MachineName; 

try 
{ 
const int SecurityImpersonation = ; 

// Call LogonUser to obtain a handle to an access token. 
bool returnValue = SecuUtil32.LogonUser( 
strLogin, 
strDomain, 
strPwd, 
(int)logonType, 
(int)logonProvider, 
ref tokenHandle); 

// Did impersonation fail? 
if (false == returnValue) 
{ 
int ret = Marshal.GetLastWin32Error(); 
// Throw the exception show the reason why LogonUser failed 
string strErr = String.Format("LogonUser failed with error code : {0}", ret); 
throw new ApplicationException(strErr, null); 
} 

// Get identity before impersonation 
bool retVal = SecuUtil32.DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle); 

// Did DuplicateToken fail? 
if (false == retVal) 
{ 
// Close existing handle 
SecuUtil32.CloseHandle(tokenHandle); 
// Throw the exception show the reason why DuplicateToken failed 
throw new ApplicationException("Failed to duplicate token", null); 
} 

// Create new identity using new primary token 
// The token that is passed to the following constructor must 
// be a primary token in order to use it for impersonation. 
WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle); 
WindowsImpersonationContext impersonatedUser = newId.Impersonate(); 

return impersonatedUser; 
} 
catch (Exception ex) 
{ 
throw new ApplicationException(ex.Message, ex); 
} 
finally 
{ 
// Close handle 
if (tokenHandle != IntPtr.Zero) 
SecuUtil32.CloseHandle(tokenHandle); 
if (dupeTokenHandle != IntPtr.Zero) 
SecuUtil32.CloseHandle(dupeTokenHandle); 
} 
} 
} 
}
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<%@ 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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2005-11-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
windows logon API
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Security; using System.Security.Principal; using System.Runtime; using System.Runtime.InteropServices; using System.Web; using System.Web.Se
阿新
2018/04/12
9850
[WCF权限控制]模拟(Impersonation)与委托(Delegation)[上篇]
由于服务操作是在寄宿进程中执行,在默认的情况下,服务操作是否具有足够的权限访问某个资源(比如文件)决定于执行寄宿进程Windows帐号的权限设置,而与作为客户端的Windows帐号无关。在有多情况下,我们希望服务操作执行在基于客户端的安全上下文中执行,以解决执行服务进行的帐号权限不足的问题。这就涉及到一个重要的话题——模拟(Impersonation)与委托(Delegation)[实例程序源代码从这里下载] 目录: 一、从访问令牌(Access Token)说起 二、再谈Windo
蒋金楠
2018/01/16
1.7K0
C# Windows服务开发
我要开发一个系统服务,服务的作用是定时检测并关闭其他应用的弹窗,但是开发后却发现,服务在运行是压根获取不到任何窗口。
码客说
2022/05/23
1.3K0
C# Windows服务开发
C#/.NET基于Topshelf创建Windows服务的守护程序不显示UI界面的问题分析和解决方案
C#/.NET基于Topshelf创建Windows服务的守护程序作为服务启动的客户端桌面程序不显示UI界面的问题分析和解决方案
Rector
2019/05/25
1.4K0
权限提升分析及防御
本篇继续阅读学习《内网安全攻防:渗透测试实战指南》,是第四章权限提升分析及防御,本章主要分析了系统的内核溢出漏洞提权、利用Windows操作系统错误配置提权、利用组策略首选项提权、绕过UAC提权、令牌窃取及无凭证条件下的权限获取,并提出了相应的安全防范措施
红客突击队
2022/09/29
1.6K0
C#使用P/Invoke来实现注册表的增删改查功能
注册表可以用来进行存储一些程序的信息,例如用户的权限、或者某些值等,可以根据个人需要进行存储和删减。
Wesky
2024/08/13
1130
C#使用P/Invoke来实现注册表的增删改查功能
使用 C# 自动化关闭电脑
我查阅资料发现有一些可使用 C# 关闭用户电脑的方法,但我觉得都不是很简洁,所以我想在这里寻找一种简单或者使用原生 .NET 关闭的方式。
zls365
2021/04/23
5880
【C#】分享基于Win32 API的服务操作类(解决ManagedInstallerClass.InstallHelper不能带参数安装的问题)
------------------201508250915更新------------------
AhDung
2018/09/13
1.5K0
从执行上下文角度重新理解.NET(Core)的多线程编程[3]:安全上下文
在前两篇文章(《基于调用链的”参数”传递》和《同步上下文》)中,我们先后介绍了CallContext(IllogicalCallContext和LogicalCallContext)、AsyncLocal<T>和SynchronizationContext,它们都是线程执行上下文的一部分。本篇介绍的安全上下文(SecurityContext)同样是执行上下文的一部分,它携带了的身份和权限相关的信息决定了执行代码拥有的控制权限。
蒋金楠
2020/12/01
5780
从执行上下文角度重新理解.NET(Core)的多线程编程[3]:安全上下文
从Win服务启动UI程序
从windows服务启动一个带UI程序的界面,这个需求在xp中是很随意的,从Vista开始似乎没有那么随意了,因为Vista中加入了Session的概念,那么什么是Session,我想这篇文章介绍的应该比我权威的多。Session隔离介绍
用户1175783
2019/09/18
1.1K0
使用WINAPI安装Windows服务[转]
using system; using system.runtime.interopservices; namespace myserviceinstaller { class serviceinstaller { #region private variables private string _servicepath; private string _servicename; private string _service
liulun
2022/05/09
5420
打印自定义纸张大小
长江支流说的办法保留太多了,结果不行,很多类都是他在程序集里自定义的,源码又没公开
Java架构师必看
2021/03/22
7870
dotnet C# 全局 Windows 鼠标钩子
本文来告诉大家一个简单的方法实现全局的 鼠标钩子 实现封装方法十分简单,请看代码 public class MouseHookEventArgs : EventArgs { public bool Handle { get; set; } /// <inheritdoc /> public MouseHookEventArgs(MouseMessages mouseMessage) { MouseMes
林德熙
2021/12/23
8000
C#进阶——记一次USB HID的各种坑(x86,x64,win10,win7)
写工控上位机的搬砖人,难免会遇到USB通讯,在一个项目中,我写的上位机使用USB HID协议和STM32通讯传输数据,从零大概花了几天找例程,找资料,最后是各种搬砖修补,终于出来了一个出版DOME,能和下位机实时通讯了。
vv彭
2022/05/10
2.8K2
.NET简谈互操作(五:基础知识之Dynamic平台调用)
我们继续.NET互操作学习。在上篇文章中我们学习了关于托管与非托管内存Dispose(释放)问题;下面我们继续学习基础知识中的Dynamic(动态)平台调用技术;
王清培
2022/03/14
4420
.NET简谈互操作(五:基础知识之Dynamic平台调用)
C#中通过API实现的打印类---修改自泥人张版本
using System; using System.Collections; using System.Text; using System.Runtime.InteropServices; using System.Security; using System.ComponentModel; using System.Drawing.Printing; namespace PrinterAPI {  public class Printer  {   private Printer()   {   }  ///泥人张版本加强版   #region API声明   [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]    internal struct structPrinterDefaults   {    [MarshalAs(UnmanagedType.LPTStr)]    public String pDatatype;    public IntPtr pDevMode;    [MarshalAs(UnmanagedType.I4)]    public int DesiredAccess;   };   [DllImport("winspool.Drv", EntryPoint = "OpenPrinter", SetLastError = true,     CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall),   SuppressUnmanagedCodeSecurityAttribute()]   internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)]    string printerName,    out IntPtr phPrinter,    ref structPrinterDefaults pd);   [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true,     CharSet = CharSet.Unicode, ExactSpelling = false,     CallingConvention = CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]   internal static extern bool ClosePrinter(IntPtr phPrinter);   [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]    internal struct structSize   {    public Int32 width;    public Int32 height;   }   [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]    internal struct structRect   {    public Int32 left;    public Int32 top;    public Int32 right;    public Int32 bottom;   }   [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]    internal struct FormInfo1   {    [FieldOffset(0), MarshalAs(UnmanagedType.I4)]    public uint Flags;    [FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)]    public String pName;    [FieldOffset(8)]    public structSize Size;    [FieldOffset(16)]    public structRect ImageableArea;   };   [StructLayout(LayoutKind.Sequential, CharSet = CharSet
jack.yang
2025/04/05
530
WPF取色器开发
前言 这里全局的键盘钩子和全局鼠标钩子是为了定义快捷键。 获取鼠标坐标 using System.Runtime.InteropServices; namespace ColorPicker.Utils { internal class ZPoint { [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern bool GetCursorPos(out POINT pt);
码客说
2022/03/13
1.9K0
.Net WinForm 提示框自动关闭
最近在开发一个简单的WinForm应用软件(WinForm是·Net开发平台中对Windows Form的一种称谓)。功能也比较简单,就是通过云小程序生成相关资料,然后通过该软件进行校验;并且与云小程序的云数据库进行连接;原型功能基本完成。但遇到一个问题就是WinForm中的MessageBox,但出后需要人手进行确认,这个问题比较麻烦,于是自己动手弄了一个简单的类。
谭广健
2021/06/09
1.9K0
利用ActiveX实现web页面设置本地默认打印机、纸张大小
通常web技术无法设置本地计算机的默认打印机,包括用代码设置纸张大小,如果业务系统中真遇到这种需求,只能通过其它辅助手段(比如ActiveX)实现。下面这段代码,出自网上被广泛使用的"泥人张打印API"(抱歉未找到原始出处),已经用C#封装了很多关于底层打印的API方法
菩提树下的杨过
2018/09/20
2.1K1
进程注入
通过 KernelCallBackTable 的进程注入涉及用自定义有效载荷替换原始回调函数,以便每当调用该函数时,都会触发有效载荷。在这种情况下,使用了 fnCOPYDATA 回调函数。
Khan安全团队
2021/12/31
5690
相关推荐
windows logon API
更多 >
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验