edcoder
edcoder

Reputation: 533

Find if user belongs to group

I want to find if the user belongs to an AD group. Can you advise how I can add that functionality using the following code?

I ask the user to enter their username and password (through a form), so not using the windows credentials. With the below code I am able to validate the user, by passing the username, and password. How can I build on the code to check if user exists in the AD Group. Is there another way to do this? Please advice

DirectoryEntry adsEntry = new DirectoryEntry("domain", userid, password); 
DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry); 
try   {   
    SearchResult adsSearchResult = adsSearcher.FindOne();
    context.Session.Timeout = 2;
    context.Session["ValidatedLoginID"] = userid;
    user.Verified = true;
    adsEntry.Close();  
} catch ( Exception ex )  {   
    // Failed to authenticate. Most likely it is caused by unknown user   
    // id or bad strPassword.   
    user.error = ex.Message;   
    adsEntry.Close();  
} 

Upvotes: 1

Views: 1322

Answers (2)

edcoder
edcoder

Reputation: 533

Here is how I solved this :

            DirectoryEntry adsEntry = new DirectoryEntry("domain", userid, password);
            DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry);
            adsSearcher.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + userid + "))";

        try
        {
            SearchResult adsSearchResult = adsSearcher.FindOne();
            string propertyName = "memberOf";
            ResultPropertyValueCollection rpvcResult = adsSearchResult.Properties[propertyName];

            foreach (Object PropertyValue in rpvcResult)
            {
                if (PropertyValue.ToString() == "Group Name")
                {
                    user.Verified = true;
                    user.FullName = GetFullName(userid);
                    adsEntry.Close();
                } else
                {
                    user.Verified = false;
                    user.error = "You do not belong to the Group so you cannot do this function";
                }
            }

        } catch (Exception ex)
        {
            user.error = "Please check your username and password credentials";
            adsEntry.Close();
        }

Upvotes: 0

aman
aman

Reputation: 6262

You can use the below code:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

 // find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

if(user != null)
{
   // check if user is member of that group
   if (user.IsMemberOf(group))
   {
     // do something.....
   } 
}

Also look at: How to check if a user belongs to an AD group?

Upvotes: 1

Related Questions