繁体   English   中英

如何通过ldap中的域名获取用户的用户名和SID

[英]How to get username and SID for user by a domain name in ldap

我正在尝试获取特定域的用户信息,该域将是程序的输入。 在域名的基础上,它应该返回用户名称/或用户的NT Id和SID的列表。 我是ldap编程的新手,任何人都可以帮助我获取此列表。

如果您使用的是.NET 3.5及更高版本并且正在讨论Active Directory,那么您应该查看System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。 在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松查找AD中的用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // do something here....     
   var usersSid = user.Sid;

   // not sure what you mean by "username" - the "DisplayName" ? The "SAMAccountName"??
   var username = user.DisplayName;
   var userSamAccountName = user.SamAccountName;
}

新的S.DS.AM使得在AD中与用户和群组玩游戏变得非常容易!

更新:如果您需要遍历域的所有用户 - 请尝试以下操作:

您可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal 
UserPrincipal qbeUser = new UserPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    UserPrincipal user = found as UserPrincipal;

    if(user != null)
    {
       // do whatever here 
       var usersSid = user.Sid;

       // not sure what you mean by "username" - the "DisplayName" ? 
       var username = user.DisplayName;
       var userSamAccountName = user.SamAccountName;
    }
}

更新#2:如果你不能(或者不想)使用S.DS.AM方法 - 这对于Active Directory来说是最简单的 - 到目前为止 - 那么你需要回退到System.DirectoryServices类和方法:

// define the root of your search
DirectoryEntry root = new DirectoryEntry("LDAP://dc=YourCompany,dc=com");

// set up DirectorySearcher  
DirectorySearcher srch = new DirectorySearcher(root);
srch.Filter = "(objectCategory=Person)";
srch.SearchScope = SearchScope.Subtree;

// define properties to load
srch.PropertiesToLoad.Add("objectSid");
srch.PropertiesToLoad.Add("displayName");

// search the directory
foreach(SearchResult result in srch.FindAll())
{
   // grab the data - if present
   if(result.Properties["objectSid"] != null && result.Properties["objectSid"].Count > 1)
   {
       var sid = result.Properties["objectSid"][0];
   }

   if(result.Properties["displayName"] != null && result.Properties["displayName"].Count > 0)
   {
       var userName = result.Properties["displayName"][0].ToString();
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM