Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello there,

i got an Issue with an Authorization of an User with an LDAP Connection to Active Directory. I want to proof if the User entered the correct Username and Password and if the user is in one specific AD Group.
How should i handle this ?
Can anyone help ?

What I have tried:

Some different code but it wasn´t the Solution for my Issue
Posted
Updated 28-Jul-20 2:36am

1 solution

1st part, verify credentials, needs System.DirectoryServices.AccountManagement
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
.. 2nd part, get groups
public List<GroupPrincipal> GetGroups(string userName)
{
   List<GroupPrincipal> result = new List<GroupPrincipal>();

   // establish domain context
   PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

   // find your user
   UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);

   // if found - grab its groups
   if(user != null)
   {
      PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();

      // iterate over all groups
      foreach(Principal p in groups)
      {
         // make sure to add only group principals
         if(p is GroupPrincipal)
         {
             result.Add((GroupPrincipal)p);
         }
      }
   }

   return result;
}
then do a LINQ query against the returned groups

This Querying and Updating Active Directory Using C# (C Sharp)[^] may also be of some use
 
Share this answer
 
v2
Comments
Sandeep Mewara 28-Jul-20 8:52am    
+5
HP91 31-Jul-20 2:07am    
Many Thanks for your help :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900