Solved

Querying LDAP for Usergroup of Specific User

Posted on 2011-03-16
8
255 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Office 365 Training for Admins - 7 Day Trial

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

Question has a verified solution.

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

Here's a look at newsworthy articles and community happenings during the last month.
This process allows computer passwords to be managed and secured without using LAPS. This is an improvement on an existing process, enhanced to store password encrypted, instead of clear-text files within SQL
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 …
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

636 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