簡體   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