Solved

Querying LDAP for Usergroup of Specific User

Posted on 2011-03-16
8
252 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

While rebooting windows server 2003 server , it's showing "active directory rebuilding indices please wait" at startup. It took a little while for this process to complete and once we logged on not all the services were started so another reboot is …
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

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