7

这必须从远程机器上获得。以下查询不适用于 SID,但适用于组和帐户名称。

"SELECT GroupComponent FROM Win32_GroupUser WHERE PartComponent = \"Win32_UserAccount.Domain='" + accountDomain + "',Name='" + accountName + "'\""

它返回的 Win32_Group 对象以字符串的形式出现,它们只有域和名称(即使 Win32_Group 具有 SID 属性)。

我有这种下沉的感觉,我将不得不:

  1. 通过查询 Win32_SID 将 SID 转换为帐户名;
  2. 执行上面的查询;
  3. 通过查询 Win32_Group将每个生成的组名称转换为 SID。
4

2 回答 2

3

您可以使用System.DirectoryServices.AccountManagement命名空间类吗?

using (var context = new PrincipalContext( ContextType.Domain ))
{
    using (var user = UserPrincipal.FindByIdentity( context, accountName ))
    {
        var groups = user.GetAuthorizationGroups();
        ...iterate through groups and find SIDs for each one
    }
}

它应该与 ContextType.Machine 一起使用,但您需要指定机器名称并拥有适当的权限。

using (var context = new PrincipalContext( ContextType.Machine,
                                           "MyComputer",
                                           userid,
                                           password ))
{
   ...
}

有一篇关于使用新的 .NET 3.5 帐户管理命名空间的不错的 MSDN文章(虽然有点长)。

于 2010-03-22T19:49:40.110 回答
3

是的,但有些方法取决于拥有一个域。

  1. 请参阅此页面了解如何使用 P/Invoke 和 Windows API 或使用 .NET 2.0+ 而没有 P/Invoke 将 SID 转换为用户 ID。

    使用 System.Security.Principal;

    // 将用户 sid 转换为域\名称 string account = new SecurityIdentifier(stringSid).Translate(typeof(NTAccount)).ToString();

  2. 如果您有 AD 和用户 ID,则使用DirectorySearcher 方法或帐户管理 API 来查找组。否则使用本文中概述的方法 获取本地组。

  3. 现在使用@tvanfosson 建议的 API 来迭代组并获取 SID。或按照以下信息。

在 ASP.NET 应用程序中,如果用户通过 Windows 身份验证而不是 Forms 身份验证,则可以使用这样的代码访问组信息。在这个例子中,我留下了一个关于在该环境中引发的异常的有趣注释,但它可能适用于其他用户:

public List<string> GetGroupsFromLogonUserIdentity()
{
    List<string> groups = new List<string>();
    HttpRequest request = HttpContext.Current.Request;

    if (request.LogonUserIdentity.Groups != null)
    {
        foreach (IdentityReference group in request.LogonUserIdentity.Groups)
        {
            try
            {
                groups.Add(group.Translate(typeof(NTAccount)).ToString());
            }
            catch (IdentityNotMappedException)
            {
                // Swallow these exceptions without throwing an error. They are
                // the result of dead objects in AD which are associated with
                // user accounts. In this application users may have a group
                // name associated with their AD profile which cannot be
                // resolved in the Active Directory.
            }
        }
    }

    return groups;
}

LogonUserIdentity 基于WindowsIdentity类。您可以修改我的代码示例以在非 Web 应用程序中使用 WindowsIdentity 和功能。一旦你遍历一个组,你应该能够做这样的事情来获取 SecurityIdentifier:

SecurityIdentifier secid = group as SecurityIdentifier;
于 2010-03-22T19:56:50.697 回答