?
Solved

Querying LDAP for Usergroup of Specific User

Posted on 2011-03-16
8
Medium Priority
?
262 Views
Last Modified: 2012-06-22
Hi All,

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 this. Im Searching alot But Everytime get new error.

LDAP Path: 192.168.1.4

Domain Name: Arslan

UserName: ArslanP

Password: testad
0
Comment
Question by:Arslan306
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 35150121
Hi there,

The following code will do that for you.
DirectorySearcher search = new DirectorySearcher("LDAP://Arslan");
            search.Filter = "(SAMAccountName=ArslanP)";

            search.PropertiesToLoad.Add("memberOf");

            SearchResultCollection results = search.FindAll();
            if (results != null)
            {
                foreach (SearchResult result in results)
                {
                    foreach (ResultPropertyValueCollection property in result.Properties.Values)
                    {
                        foreach (object obj in property)
                        {
                            Console.WriteLine("Group: " + obj.ToString());
                            
                        }
                    }
                }
            }

Open in new window

0
 

Author Comment

by:Arslan306
ID: 35151966
Hi angus,

I Still Have confusion with your given code snippet. The Reason is You Specified This in Your Code

DirectorySearcher search = new DirectorySearcher("LDAP://Arslan"); \\ Arslan is My Domain Name Not My LDAP Path So I Think It Will Not Search That And Other Reason I Think Is For Directory Searcher Method We Also Need Obejct Of Directory Entry That Takes LDAP Path UserName And Password To Communicate With AD. Can You Please Explain Me On That Points.

Thanks
0
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 35155124
Hi Arslan,

In the example that should search on your Domain, but appologies I didn't see your LDAP path in your original post.   On your second point I will certainly try and help you.

You could try and change the following:
DirectorySearcher search = new DirectorySearcher("LDAP://Arslan");
search.Filter = "(SAMAccountName=ArslanP)";

To:
DirectoryEntry entry = new DirectoryEntry("192.168.1.4://Arslan", "ArslanP", "testad");
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=ArslanP)";
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 
LVL 15

Expert Comment

by:Russell_Venable
ID: 35160591
@angus_young_acdc, Wouldn't it be better to use it like so. Just trying to help out.

// You forgot to add LDAP protocol then define "CN=username", "DC=domain", etc. Rest is good. Other then not ending the connection maybe.
DirectoryEntry entry = new DirectoryEntry("LDAP://192.168.1.4,CN=ArslanP,DC=192.168.1.4,DC=com");
entry.Username = "ArslanP";
entry.Password = "testad";
entry.AuthenticationType = AuthenticationTypes.Secure;

DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + entry.Username + ")";
search.PropertiesToLoad.Add("memberOf");
SearchResultCollection results2 = search.FindAll();
if (results2 != null)
{
   foreach (SearchResult result in results2)
   {
       foreach (ResultPropertyValueCollection property in result.Properties.Values)
       {
           foreach (object obj in property)
           {
               Console.WriteLine("Group: " + obj.ToString());
           }
       }
   }
}
// Close Connection
entry.Dispose();
search.Dispose();
results.Dispose();

Open in new window

Cheers!
0
 
LVL 6

Expert Comment

by:judgeking
ID: 35162454
Russell, nice work!  Maybe you'll get yourself some more points for re-writing someone else's code!  Sympathies angus...
0
 
LVL 15

Expert Comment

by:Russell_Venable
ID: 35162739
Thanks for showing your maturity and unprofessionaliam. I told the OP it was your code and explained how it worked along with how it was insecure and how to fix it. Frankly I am suprised he did what he did. He was in a hurry a well as he stated. You showed him how to do it in a insecure manor, without fixing it to his needs, without making it more attractive, nor did make you make it for a domain, give a commandline or release resources.

I am pretty sure if you where hired to do this you would get fired just as quickly.  Stop stalking me.  Take some time off. It's not my fault he choose it instead of you. You would think that if someone came along to help out they would be appreciative and thankful that they learned something new.  Besides when it was done it was more then twice the size so thats not really a rewrite now is it? Yours was 14 lines and mine was 25!!!! So now your going to stalk me? That's real mature... Just pay more careful attention to OP's post and respond in a smarter way they will respect you for that. I am pretty sure that if you payed for a service you would want it timely and professioanlly done. This place is about help I could care less about the points. It does not define me. My real work saves lives(That does!). Few if not none of the people here can claim such a thing. So when it is commented upon to improve take a look at it and learn from it, don't lash out at people it just shows Ill temperament and immaturity.
0
 

Accepted Solution

by:
Arslan306 earned 0 total points
ID: 35706704
Hi I Found The Solution Myself. Hope this will help You

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,"ElizaPurton");
        ctx.ValidateCredentials(txtUsername.Text, txtPassword.Text);


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

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

        return result;
    }
0
 

Author Closing Comment

by:Arslan306
ID: 35735889
it Works for Me
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn't it be nice if objects in Active Directory automatically moved into the correct Organizational Units? This is what AutoAD aims to do and as a plus, it automatically creates Sites, Subnets, and Organizational Units.
Transferring FSMO roles is done when an admin wants to split roles between certain Domain Controllers or the Domain Controller holding the Roles has been forcefully demoted using dcpromo / forceremoval
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…
Suggested Courses

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question