我的问题
我正在使用 PInvoked Windows API 函数来验证用户是否属于本地管理员组。我正在利用GetCurrentProcess
, OpenProcessToken
, GetTokenInformation
and LookupAccountSid
验证用户是否是本地管理员。
GetTokenInformation
返回一个TOKEN_GROUPS
具有数组的结构体SID_AND_ATTRIBUTES
结构。我迭代该集合并比较返回的用户名LookupAccountSid
.
我的问题是,在本地(或更普遍地在我们的内部域上),这按预期工作。 builtin\Administrators 位于当前进程令牌的组成员身份内,我的方法返回 true。在另一个开发人员的另一个域上,该函数返回 false。
The LookupAccountSid
前 2 次迭代功能正常TOKEN_GROUPS
struct,返回 None 和Everyone,然后抱怨“参数不正确”。
什么会导致只有两个组正常工作?
The TOKEN_GROUPS
struct表示有14组。我假设 SID 无效。
我 PInvoke 上的所有内容均取自 PInvoke 上的示例website http://www.pinvoke.net/。唯一的区别是,与LookupAccountSid
我已经改变了Sid
参数来自abyte[]
to a IntPtr
因为SID_AND_ATTRIBUTES
也定义为IntPtr
。这样可以吗?LookupAccountSid
是用 PSID 定义的吗?
LookupAccountSid PInvoke
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool LookupAccountSid(
string lpSystemName,
IntPtr Sid,
StringBuilder lpName,
ref uint cchName,
StringBuilder ReferencedDomainName,
ref uint cchReferencedDomainName,
out SID_NAME_USE peUse);
代码失败的地方
for (int i = 0; i < usize; i++)
{
accountCount = 0;
domainCount = 0;
//Get Sizes
LookupAccountSid(null, tokenGroups.Groups[i].SID, null, ref accountCount, null,
ref domainCount, out snu);
accountName2.EnsureCapacity((int) accountCount);
domainName.EnsureCapacity((int) domainCount);
if (!LookupAccountSid(null, tokenGroups.Groups[i].SID, accountName2, ref accountCount, domainName,
ref domainCount, out snu))
{
//Finds its way here after 2 iterations
//But only in a different developers domain
var error = Marshal.GetLastWin32Error();
_log.InfoFormat("Failed to look up SID's account name. {0}", new Win32Exception(error).Message);
continue;
}
如果需要更多代码,请告诉我。任何帮助将不胜感激。