这必须从远程计算机获取。以下查询不适用于 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。
有帮助吗?

解决方案

你可以使用 系统.目录服务.帐户管理 命名空间类?

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 ))
{
   ...
}

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

其他提示

是的,但有些方法依赖于拥有域。

  1. 看到这个 有关如何使用P/Invoke和Windows API或.NET 2.0+且无P/Invoke将SID转换为用户ID。

    使用 System.Security.Principal;

    //将用户SID转换为域名称字符串帐户= new SecuritySidentifier(stringsID).translate(typeof(ntacCount))。toString();

  2. 如果您有广告和用户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;
}

登录用户身份基于 Windows身份识别 班级。您可以修改我的代码示例以在非 Web 应用程序中使用 WindowsIdentity 和函数。一旦你迭代一个组,你应该能够执行类似的操作来获取 SecurityIdentifier:

SecurityIdentifier secid = group as SecurityIdentifier;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top