Solved

Querying LDAP for Usergroup of Specific User

Posted on 2011-03-16
8
253 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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.
A company’s centralized system that manages user data, security, and distributed resources is often a focus of criminal attention. Active Directory (AD) is no exception. In truth, it’s even more likely to be targeted due to the number of companies …
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 …
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

749 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