在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);
posted on 2009-09-11 13:56  周雪峰  阅读(588)  评论(0编辑  收藏  举报