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.Security;
namespace Impersonate
{
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
struct _USE_INFO_2
{
internal string ui2_local;
internal string ui2_remote;
internal IntPtr ui2_password; // don't pass a string or StringBuilder here!!
internal uint ui2_status;
internal uint ui2_asg_type;
internal uint ui2_refcount;
internal uint ui2_usecount;
internal string ui2_username;
internal string ui2_domainname;
}
class WinNet
{
[DllImport("netapi32", CharSet=CharSet.Auto, SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int NetUseAdd(
string UncServerName, // not used
int Level, // use info struct level 1 or 2
IntPtr Buf, // Buffer
ref int ParmError
);
const uint USE_WILDCARD = 0xFFFFFFFF;
// Establish a use record
public static void UseRecord(string resource, string user, string
password, string domain)
{
int ret = 0;
int paramError = 0;
_USE_INFO_2 use2 = new _USE_INFO_2();
IntPtr pBuf = IntPtr.Zero;
use2.ui2_password = IntPtr.Zero;
try
{
pBuf = Marshal.AllocHGlobal(Marshal.SizeOf(use2));
use2.ui2_local = null;
use2.ui2_asg_type = USE_WILDCARD;
use2.ui2_remote = resource;
use2.ui2_password = Marshal.StringToHGlobalAuto(password);
use2.ui2_username = user;
use2.ui2_domainname = domain;
Marshal.StructureToPtr(use2, pBuf, true);
ret = NetUseAdd(null, 2, pBuf, ref paramError);
if(ret != 0)
{
throw new Exception(new
Win32Exception(Marshal.GetLastWin32Error()).Message);
}
}
finally
{
Marshal.FreeHGlobal(use2.ui2_password);
Marshal.FreeHGlobal(pBuf);
}
}
}
class Program
{
[System.Runtime.InteropServices.DllImport("advapi32.dll")]
public static extern int LogonUser(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);
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
static public WindowsImpersonationContext wic;
//static void Main(string[] args)
//{
// IntPtr lnToken;
// if (ImpersonateValidUser("michaell", "cmp-0641", "wilma"))
// {
// using (wic)
// {
// string dir = @"\\cmp-0641\C$\" + "Test";
// System.IO.Directory.CreateDirectory(dir);
// }
// StringBuilder sb = new StringBuilder(80, 80);
// RevertToSelf();
// //CloseHandle( lnToken );
// }
// else
// {
// }
// return;
//}
static public bool ImpersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity wi;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
wi = new WindowsIdentity(tokenDuplicate);
wic = wi.Impersonate();
if (wic != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
}
public class LogOnUser
{
//LogonUser parameters
[DllImport("advapi32.dll")]
private static extern bool LogonUser(String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
//CloseHandle parameters. When you are finished,
//free the memory allocated for the handle.
[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);
public static WindowsIdentity GetWindowsIdentity(string pUserName, string pDomain)
{
return null;
}
public static WindowsIdentity GetWindowsIdentity(string pUserName, string pDomain, string pPassword)
{
IntPtr tokenHandle = IntPtr.Zero;
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_NETWORK = 5;
//Call LogonUser to obtain a
//handle to an access token
bool returnValue = LogonUser(pUserName, pDomain,
pPassword,
LOGON32_LOGON_NETWORK,
LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
if (false == returnValue)
{
return null;
}
////Check the identity
//Console.WriteLine("Before impersonation: " +
// WindowsIdentity.GetCurrent().Name);
//Create a WindowsIdentity from the impersonation
//token, then impersonate the user.
WindowsIdentity newId;
newId = new WindowsIdentity(tokenHandle);
return newId;
}
catch (Exception ex)
{
// TODO log the Exception Message.
return null;
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix