UserPrincipal.IsMemberOf is returning false
Asked Answered
R

2

7

I am trying to validate the user is in the "TestGroup" group or not. The user is part of the "TestGroup" group, even i am getting the retval = false @line(retVal = user.IsMemberOf(groupPrincipal);), and in event viewer it is showing msg as "The user name or password is incorrect".

Can you help me in this.

string userName = this.Request.ServerVariables["AUTH_USER"];
if (ValidateUser(userName) == false)
      Response.Redirect("Error.aspx?errormsg=" + userName + " does not have permission to view this page");

 public static bool ValidateUser(String userName)
        {
            bool useGroupAuthorization = true;
            if (useGroupAuthorization)
                return GroupLookup(userName, "TestGroup");            
} 

private static bool GroupLookup(string userName, string groupName)
        {
            System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
            appLog.Source = "Test App";
            bool retVal = false;
            PrincipalContext pc = null;
            UserPrincipal user = null;
            GroupPrincipal groupPrincipal = null;

            try
            {
                string strdomain = "TestDomain"; 
                pc = new PrincipalContext(ContextType.Domain,strdomain);

                user = UserPrincipal.FindByIdentity(pc, userName);

                groupPrincipal = GroupPrincipal.FindByIdentity(pc, groupName);     

                retVal = user.IsMemberOf(groupPrincipal);

            }
            catch (NoMatchingPrincipalException nmpx)
            {              
                appLog.WriteEntry(nmpx.Message);
            }
            catch (PrincipalOperationException pox)
            {
               appLog.WriteEntry(pox.Message);
            }
            catch (Exception ex)
            {
                if (user == null)
                {

                    appLog.WriteEntry(ex.Message);
                }
                else
                {
                    appLog.WriteEntry(ex.Message);
                }
            }
            return retVal;
        }




    // when i tried with below code i am getting userPrincipal is null

     //    bool retVal = false; string strdomain = "TestDomain";
        //    PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain, strdomain);
        //      UserPrincipal queryByExampleUser = new UserPrincipal ( principalCtx );
        //      queryByExampleUser.SamAccountName = userName;
        //      PrincipalSearcher principalSearcher = new PrincipalSearcher ( );
        //      principalSearcher.QueryFilter = queryByExampleUser;
        //      UserPrincipal userPrincipal = principalSearcher.FindOne ( ) as UserPrincipal;

        //      retVal =  IsUserInGroup("TestGroup", userPrincipal);

        //      return retVal;
        // }

        //static bool IsUserInGroup(string groupName, UserPrincipal user)
        //{
        //    PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        //    GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, groupName);
        //    if (user.IsMemberOf(groupPrincipal))
        //    {
        //        return true;
        //    }
        //    return false;
        //}
Rooseveltroost answered 25/8, 2014 at 17:17 Comment(2)
Are you sure the user is part of the TestGroup, and not part of a group that is part of the TestGroup? IsMemberOf does not recurse through nested groups.Metanephros
sorry for late comments.yes the user is part of that group.Rooseveltroost
M
4

"gpKnownAccountToCheck.Members" not recursive.

Need use method: GetMembers(recursive: true)

 var result = groupPrincipal
                    .GetMembers(true)
                    .Where(x => x.Sid == userPrincipal.Sid)
                    .Count() > 0;
Mooncalf answered 29/6, 2019 at 6:27 Comment(1)
This approach really misses out on performing much faster with a very simple change. .Where(x => x.Sid == userPrincipal.Sid).Count() > 0; is going to iterate through all the values, then count them up to reach a total, and then compare the total with zero. By replacing that with .Any(x => x.Sid == userPrincipal.Sid); it would stop iterating at the first one it finds.Mairemaise
J
1

UserPrincipal.IsMemberOf(GroupPrincipal) seems to work with some groups and not others. On my domain, it worked with domain\Developers (custom group) but not domain\Domain Users. Go figure. I halted the code in the debugger and examined the list of members of the Domain Users group and found my user in there, but IsMemberOf still returned false. However, I found if I looped through the UserPrincipal object collection in GroupPrincipal.Members I could do the check that way by comparing the UserPrincipal in the collection to the the one I was searching for. Crappy, but the only reliable solution I could find.

Sample code:

string sAccountToCheckSID = upAccountToCheck.Sid.Value;
foreach(UserPrincipal up in gpKnownAccountToCheck.Members)
{
     string sKnownSIDInGroup = up.Sid.Value;
     if(sKnownSIDInGroup.Equals(sAccountToCheckSID))
     {
          userMatchingUserObject = userKnownUser;
          return true;
     }
}

So I don't have the WHY. But that's my work around.

Jackelynjackeroo answered 23/4, 2018 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.