0

Following code returns True if the user has been added to a certain SP Group directly. However it returns False if the user is added via an AD Group. How do I fix it so that it returns true even if the user has not been added to the SP Group directly but via an AD Group?

bool userInGroup = user.Groups.Cast<SPGroup>().Any(g => g.ID == theGroup.ID);

I have tried this one it casts an exception and says the User does not exists in the Group. but the user exists in an AD Group which has been added to the SP Group.

bool userInGroup = theGroup.Users[user.LoginName] != null;
  • Are you trying to check if a user is a member of a SPGroup? – Amal Hashim Jan 26 '15 at 19:17
  • yes I am trying to check if a user is a member of a SPGroup – Medes Jan 26 '15 at 19:22
1

I found the below snippet

using System.DirectoryServices.AccountManagement;

public bool IsUserInSharePointGroup(string webUrl, string groupName, string username)
{
    bool userIsInGroup = false;
    SPSecurity.RunWithElevatedPrivileges(delegate
    {
        try
        {
            SPWeb web = SPContext.Current.Web;
            // Find the group
            SPGroup group = web.SiteGroups[groupName];
            string upperCaseUserName = username.ToUpper();
            foreach (SPUser user in group.Users)
            {
                // Check if this is an AD Group
                if (!user.IsDomainGroup)
                {
                    // Verify if the user name matches the user name in group
                    if (user.LoginName.ToUpper().Equals(upperCaseUserName))
                    {
                        userIsInGroup = true;
                        return;
                    }
                }
                else
                {
                    // this is an AD group
                    var pc = new PrincipalContext(ContextType.Domain);
                    var myuser = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, username);
                    var mygroup = GroupPrincipal.FindByIdentity(pc, user.LoginName);
                    if (myuser.IsMemberOf(mygroup))
                    {
                        userIsInGroup = true;
                        return;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            //Trace error
        }
    });
    return userIsInGroup;
}

http://www.bigscholar.com/2012/01/06/check-if-user-is-in-a-sharepoint-or-ad-group/

  • this does not solve my problem becuase this line of code returns null. var mygroup = GroupPrincipal.FindByIdentity(pc, user.LoginName); – Medes Jan 26 '15 at 19:58
  • Debug and review what is the value in user.LoginName. – Amal Hashim Jan 26 '15 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.