How to get username and SID for user by domain name in ldap

I am trying to get user information for a specific domain, which will be a contribution to the program. Based on the domain name, it should return a list of username / or NT ID and SID of the user. I'm new to ldap programming, can someone help me get this list.

+6
source share
1 answer

If you are using .NET 3.5 and discussing Active Directory, you should check the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read more here:

Basically, you can define the context of a domain and easily find users and / or groups in 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; } 

The new S.DS.AM makes it very easy to play with users and groups in AD!

Update: if you need to go through all users of the domain, try the following:

You can use PrincipalSearcher and "query by example" to perform a search:

 // 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; } } 

Update # 2: if you cannot (or don't want) to use the S.DS.AM approach, which is the easiest for Active Directory, of course, you need to return to the classes and methods of 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(); } } 
+15
source

Source: https://habr.com/ru/post/909517/


All Articles