在Windows线程中模拟其他用户上下文!

在Windows线程中模拟其他用户上下文,需要使用WindowsIdentity.Impersonate方法!同时还需要用LogonUser API来获取安全令牌,代码如下:
using System.Runtime.InteropServices;
using System.Security.Principal;
class Program
{
[DllImport("Advapi32.dll")]
static extern bool LogonUser(
string sUserName,
string sDomain,
string sUserPassword,
uint dwLogonType,
uint dwLogonProvider,
out System.IntPtr token);

[DllImport("Kernel32.dll")]
static extern void CloseHandle(System.IntPtr token);

static void Main()
{
System.IntPtr pToken;
if(LogonUser(
"Administrator",
"DomainName",
"Password",
2,
0,
out pToken)){
WindowsIdentity.Imersonate(pToken);//模拟用户
WindowsIdentity id=WindowsIdentity.GetCurrent();
Console.WriteLine(id.Name);
CloseHandle(pToken);
原文地址:https://www.cnblogs.com/xuefeng1982/p/1564736.html