我有一个用户帐户的SID,我想要它所属的组的SID

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

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

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

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

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

您可以使用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 文章 (虽然很长)。

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

  1. 有关如何使用P / Invoke和Windows API,或使用.NET 2.0+和无P / Invoke将SID转换为用户ID的信息,请参阅此页面 。

    使用System.Security.Principal;

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

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

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

在ASP.NET应用程序中,可以使用此类代码访问组信息,前提是用户通过Windows进行身份validation,而不是表单身份validation。 在这个例子中,我留下了一个关于在该环境中引发的exception的有趣说明,但它可能适用于其他用户:

 public List GetGroupsFromLogonUserIdentity() { List groups = new List(); 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类。 您可以修改我的代码示例以使用WindowsIdentity并在非Web应用程序中运行。 一旦你遍历一个组,你应该能够做这样的事情来获得SecurityIdentifier:

 SecurityIdentifier secid = group as SecurityIdentifier;