Solved

Querying LDAP for Usergroup of Specific User

Posted on 2011-03-16
8
251 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
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
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

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Resolve DNS query failed errors for Exchange
In this article, I am going to show you how to simulate a multi-site Lab environment on a single Hyper-V host. I use this method successfully in my own lab to simulate three fully routed global AD Sites on a Windows 10 Hyper-V host.
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 video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

809 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