【发布时间】:2011-05-15 06:28:21
【问题描述】:
我发现了一些示例代码on codeproject 允许用户模拟。
此代码通过导入以下非托管 Win32 API 函数来工作:
[DllImport("advapi32.dll", SetLastError = true)]
private 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)]
private static extern int DuplicateToken(IntPtr hToken,int impersonationLevel,ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);
这些函数用于模拟目标用户,然后执行一些操作,然后还原模拟上下文。模拟用户是这样实现的:
if ( LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT, ref token ) != 0 )
{
if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 )
{
tempWindowsIdentity = new WindowsIdentity( tokenDuplicate );
impersonationContext = tempWindowsIdentity.Impersonate();
}
}
我试图了解为什么此代码首先使用LogonUser 获取所需的令牌,然后复制该令牌,然后再对复制的令牌执行模拟。为什么不直接使用从LogonUser 方法获得的令牌进行模拟。
显然写这篇文章的人比我更了解这一点,所以看起来我错过了一些东西。我能否解释一下为什么需要此过程中看似多余的令牌复制步骤?
【问题讨论】:
-
这是 codeproject,不是 codeplex,对吧?
-
正确,是的,现在已经更新了,谢谢。
标签: c# windows winapi authentication