简体   繁体   中英

Determine usergroups/claims of user given LDAP server details in C#

We have a test active directory LDAP server. I also have some user names and passwords. I would like to determine the claims/user groups of a particular user, whilst logged into another domain. Can this be done with some C# code? I presume I will have to use System.DirectoryServices.dll

If you can use .Net 3.5 of higher, then try System.DirectoryServices.AccountManagement.dll assembly. It provides System.DirectoryServices.AccountManagement namespace and Principal-based classes, such as UserPrincipal and GroupPrincipal. They represent higher level of abstraction and are easier to use.

For example, to connect to LDAP server in another domain (get Principal Context in terms of this abstraction) you need to create an instance of PrincipalContext class with this constructor :

PrincipalContext anotherDomainContext = new PrincipalContext(ContextType.Domain, DomainDnsName, RootOU, ContextOptions.SimpleBind, QueryUserName, QueryUserPassword);

RootOU is something like "DC=Company,DC=COM", therefore DomainDnsName will be like "company.com" or "ldapserver.company.com". If you have serveral domains in your AD forest then try to connect to global catalog (DomainDnsName = "ldapserver.company.com:3268"). QueryUserName and QueryUserPassword are plain strings with username and password which are used to connect to LDAP server. Username may include domain name, for example:

string QueryUserName = @"company\username";

Once connected to LDAP server you can search for users:

 UserPrincipal user = UserPrincipal.FindByIdentity(anotherDomainContext , IdentityType.SamAccountName, samAccountName);

where you supply samAccountName and context (connection).

With an instance of UserPrincipal at hands you gain access to its properties and methods . For example, get security groups for user:

PrincipalSearchResult<Principal> searchResults = user.GetGroups();
List<GroupPrincipal> groupsList = searchResults.Select(result => result as GroupPrincipal).
            Where(group => (group != null) &&
                           (group.IsSecurityGroup.HasValue) &&
                           (group.IsSecurityGroup.Value))

Note that GetGroups returns only groups to which user belongs directrly. To get all user groups including nested, call GetAuthorizationGroups . Also, you can avoid using LINQ, it's just for filtering security groups from GetGroups.

With GroupPrincipal you can check Name property, or Members collecion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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