代码之家  ›  专栏  ›  技术社区  ›  Adam Driscoll

标识用户是否在本地administrators组中

  •  2
  • Adam Driscoll  · 技术社区  · 14 年前

    我正在使用PinvokedWindowsAPI函数来验证用户是否属于本地管理员组。我在利用 GetCurrentProcess OpenProcessToken , GetTokenInformation LookupAccountSid 验证用户是否为本地管理员。

    GetTokenin信息 TOKEN_GROUPS 结构的数组 SID_AND_ATTRIBUTES 结构。我遍历集合并比较 .

    我的问题是,在本地(或者更广泛地说,在我们的内部领域),这和预期一样有效。builtin\Administrators位于当前进程令牌的组成员身份中,my方法返回true。在另一个开发人员的另一个域上,函数返回false。

    这个 查找帐户SID 令牌组 struct,返回None和everybody,然后抱怨“参数不正确”

    什么会导致只有两组工作正常?

    令牌组 struct表示有14个组。我假设是SID无效。

    website . 唯一的区别是 查找帐户SID 我改变了主意 Sid byte[] IntPtr 因为 也定义为 IntPtr公司 查找帐户SID

    查找帐户Sid 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;
                        }
    

    如果需要更多的代码,请告诉我。任何帮助都将不胜感激。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Jerry Coffin    14 年前

    听起来你想复制 NetUserGetLocalGroups . 你也可以使用 NetUserGetInfo 信息级别为1,并检查 usri1_priv USER_INFO_1 对于 USER_PRIV_ADMIN .

        2
  •  2
  •   Anders    14 年前

    我不确定NetUserGetLocalGroups是否知道deny SIDs(如果需要验证当前进程(不是用户帐户!)在管理组中,您必须处理拒绝SID)

    如果您只需要支持2000及更高版本,PInvoke CheckTokenMembership (该MSDN页具有IsUserAdmin示例函数)