开发者

Querying LDAP for Usergroup of Specific User

开发者 https://www.devze.com 2023-02-17 19:35 出处:网络
I have to check usergroups of LDAP Active Directory for a specific user in C#. Mean I pass this username to a method and it returns me list of group from that user belongs. Can You Please help me in t

I have to check usergroups of LDAP Active Directory for a specific user in C#. Mean I pass this username to a method and it returns me list of group from that user belongs. Can You Please help me in th开发者_开发百科is. Im Searching alot But Everytime get new error.

LDAP Path: 192.168.1.4

Domain Name: Arslan

UserName: ArslanP

Password: testad


Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5

Basically, add a reference to the assembly System.DirectoryServices.AccountManagement, and then you can define a domain context and easily find users and/or groups in AD:

using System.DirectoryServices.AccountManagement;

public List<GroupPrincipal> GetGroupsForUser(string username)
{
  List<GroupPrincipal> result = new List<GroupPrincipal>();

  // set up domain context - if you do a lot of requests, you might
  // want to create that outside the method and pass it in as a parameter
  PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

  // find user by name
  UserPrincipal user = UserPrincipal.FindByIdentity(username);

  // get the user's groups
  if(user != null)
  {
     foreach(GroupPrincipal gp in user.GetAuthorizationGroups())
     {
         result.Add(gp);
     }    
  }

  return result;
}

The new S.DS.AM makes it really easy to play around with users and groups in AD:


This related question may help you:

Get List of Users From Active Directory In A Given AD Group

It asks the reverse question, which is how to qet a list of users when you know the group, but other answers may be of use to you as well.

See also the answer to this question:

How to get all the AD groups for a particular user?

0

精彩评论

暂无评论...
验证码 换一张
取 消