1
votes

I am using below C# code to check whether the user is part of required domain member group.

The passing username is part of 3 member groups but the code is returning the first domain group member name and exit from the for loop. Please help me to get entire list of domain group for the user.

bool bReturn = false;
string sDomainName = System.Environment.UserDomainName;
using (PrincipalContext oContext = new     PrincipalContext(ContextType.Domain, sDomainName))
{
if (oContext.ValidateCredentials(sUserName, sPassword))
{
    using (PrincipalSearcher oSearcher = new PrincipalSearcher(new UserPrincipal(oContext)))
    {
        oSearcher.QueryFilter.SamAccountName = sUserName;
        Principal oPrincipal = oSearcher.FindOne();
        foreach (Principal oPrin in oPrincipal.GetGroups())
        {
            if (oPrin.Name.Trim().ToString().Equals(sGroupName))
            {
                bReturn = true;
                break;
            }
        }
    }
}
3
you're are very funny :-)Jazb

3 Answers

0
votes

tell me if I got it wrong. I can only see one purpose, to return bool? btw, even if that's not the case, try removing break;

bool bReturn = false;

string sDomainName = System.Environment.UserDomainName;
using (PrincipalContext oContext = new     PrincipalContext(ContextType.Domain, sDomainName))
{
if (oContext.ValidateCredentials(sUserName, sPassword))
{
    using (PrincipalSearcher oSearcher = new PrincipalSearcher(new UserPrincipal(oContext)))
    {
        oSearcher.QueryFilter.SamAccountName = sUserName;
        Principal oPrincipal = oSearcher.FindOne();
        foreach (Principal oPrin in oPrincipal.GetGroups())
        {
            if (oPrin.Name.Trim().ToString().Equals(sGroupName))
            {
                //your stuff here (assign vars, values etc)
                bReturn = true; // <-- 
            }
        }
    }
}

because based on the logic that you use, if it meets one condition it will stop the loop.

0
votes

Instead of your loop, use the IsMemberOf method:

bReturn = oPrincipal.IsMemberOf(oContext, IdentityType.Name, sGroupName);

That will probably work for you. But keep in mind that this (and your loop method) will only work if the group is listed in the memberOf attribute of the user. If:

  1. You have more than one domain in your AD forest, and
  2. The group you are working with is Global or Domain Local, and
  3. The group is not on the same domain as the user

then it will not work.

I talk about that in one of the articles I wrote on my site: Find out if one user is a member of a group

0
votes

The c# code unable to fetch AD membership details coz of privilege issue. I have used net group "<GroupName>" to get the list of users as part of the group and then checked the required user in the list.

It is one another option to verify the user is member of required group.