如何扮演另一个帐号(c#实现)
author:dahuaidan410
from:cnblogs
using directives#region using directives
using system;
using system.security.principal;
using system.runtime.interopservices;
using system.text.regularexpressions;
#endregion
namespace impersonal
{
class program
{
测试代码#region 测试代码
public static void main(string[] args)
{
console.writeline(“当前用户是: “
+ windowsidentity.getcurrent().name);
impersonatedwork testdel = new impersonatedwork(test);
impersonateanddo(“epro\\liping”, “88888888”, testdel);
console.writeline(“当前用户是: “
+ windowsidentity.getcurrent().name);
}
static void test()
{
console.writeline(“当前用户是: “
+ windowsidentity.getcurrent().name);
}
#endregion
[dllimport(“advapi32.dll”, setlasterror = true)]
public extern static bool logonuser(string lpszusername, string lpszdomain,
string lpszpassword, int dwlogontype,
int dwlogonprovider, ref intptr phtoken);
[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 delegate void impersonatedwork();
/**//// <summary>
/// 以指定用户的身份去做一件事情
/// </summary>
/// <param name=”username”></param>
/// <param name=”pwd”></param>
/// <param name=”whattodo”></param>
public static void impersonateanddo(string username, string pwd, impersonatedwork whattodo)
{
扮演用户#region 扮演用户
string domainname = string.empty;
string username = string.empty;
intptr tokenhandle = new intptr(0);
intptr dupetokenhandle = new intptr(0);
const int logon32_provider_default = 0;
const int logon32_logon_interactive = 2;
const int securityimpersonation = 2;
if (! regex.ismatch(username, @”^\w+[\\]?\w+$”))
{
throw new applicationexception(“非法的用户名”);
}
string[] tmp = username.split(new char[] { \\ });
if (tmp.length > 1)
{
domainname = tmp[0];
username = tmp[1];
}
else
{
username = tmp[0];
}
tokenhandle = intptr.zero;
dupetokenhandle = intptr.zero;
bool returnvalue = logonuser(username,domainname, pwd,
logon32_logon_interactive, logon32_provider_default,
ref tokenhandle);
if (!returnvalue)
{
throw new applicationexception(“取handle出错了!”);
}
//console.writeline(“当前用户是: “
// + windowsidentity.getcurrent().name);
bool retval = duplicatetoken(tokenhandle, securityimpersonation, ref dupetokenhandle);
if (!retval)
{
closehandle(tokenhandle);
throw new applicationexception(“复制handle出错了!”);
}
windowsidentity newid = new windowsidentity(dupetokenhandle);
windowsimpersonationcontext impersonateduser = newid.impersonate();
#endregion
以新用户身份调用#region 以新用户身份调用
whattodo();
#endregion
取消扮演#region 取消扮演
impersonateduser.undo();
if (tokenhandle != intptr.zero)
closehandle(tokenhandle);
if (dupetokenhandle != intptr.zero)
closehandle(dupetokenhandle);
#endregion
}
}
}