Click here to Skip to main content
1,837 members
Articles / Multimedia / C#
Article

Check Whether User Exists in Active Directory

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
12 Apr 2012CPOL 5.4K  
Handle Active Directory users in SharePoint

Introduction

This article describes a simple approach to determining whether or not a logged in user is a member of a group within the context of an Sharepoint web based application. The approach shown is based on the use of Windows based authentication in a web site configured to deny anonymous authentication and to require Windows based authentication and redirect the user according to their permission level. So I need to check in which group the user belongs.

The example shown would be useful on a company intranet site in which it was, for example, necessary to restrict access to certain parts of the available functionality based upon the member's role. For example, you might be working with an application that has administrative and general users; the administrative users might have additional application rights such as the ability to delete records. If one were to check for group membership in the administrator's group, the application can show or hide such functionality by getting the currently logged in user and checking whether or not that user is a group member.

I had to check whether the current user exits or not. As per my requirement, I have created different groups with different privileges in Active Directory(AD) and added multiple users to each group. Then I created multiple Sharepoint Groups in a site and added Active Directory User group in appropriate Sharepoint group as per the permission level.

Here, I have a written a generic class to support this type of functionality.

Technical Steps

  1. It will get all existing Sharepoint groups from the site collection.
  2. Loop into Groups and check each member of the group whether the member is a domain user group (as we have added Active domain group as member of sharepoint group) or a Sharepoint user.
  3. If it is a Sharepoint user, then it checks whether this is the current user? If not, return false.
  4. If the user is in the domain user Group, it collects all users under that user group and loops the list to that try to find the current user. If a user is found, it returns true, otherwise returns false.

Code

C#
public class UserManager{ 
// Checking whether the current user is a member of a specified
// Sharepoint group public bool IsCurrentUserInRole(string SharepointGroupName)
{
    bool flag = false;
    try {
        string strUsername = SPContext.Current.Web.CurrentUser.LoginName;
        string webUrl = SPContext.Current.Web.Url; 
        // Check the role of user return CheckRole(username, userrole, webUrl); 
    }
    catch (Exception ex)
    {
        // log the error
    }
    return flag; 
}

// First Check the role of user in share point groups 
private bool CheckRole(string username, string userrole, string webUrl)
{
    if (IsUserInSharePointGroup(webUrl, userrole, username))
        return true;
    else return false;
}

public bool IsUserInSharePointGroup(string webUrl, string groupName, string username)
{
    bool reachedMax = false;
    bool userIsInGroup = false; 
    // return false if there are invalid inputs
    if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(groupName))
        return false;
    // The Run with elevated privileges needs read permission
    // on active directory and the ability to run directory code.
    SPSecurity.RunWithElevatedPrivileges(delegate {
        try {
            // Get the Site Collection
            using (SPSite site = new SPSite(webUrl))
            {
                // Get the web
                using (SPWeb web = site.OpenWeb())
                {
                    // Find the group
                    SPGroup group = site.RootWeb.SiteGroups[groupName]; 
                    string upperCaseUserName = username.ToUpper();
                    // Get ad users in the groups. Since MOSS does
                    // not support nested groups
                    // this will always be a collection of AD users
                    // and groups
                    foreach (SPUser user in group.Users)
                    {
                        // Check if this is a Group
                        if (!user.IsDomainGroup)
                        {
                            // Verify if the user name matches the user name in group
                            if (user.LoginName.ToUpper().Equals(upperCaseUserName))
                            {
                                // if a match is confirmed, return from the method.
                                // There is no need to continue
                                userIsInGroup = true;
                                return; 
                            }
                        }
                        else {
                        // If the AD entity is a User Group,
                        // then check for users in that group
                        if (IsUserInADGroup(web, user.LoginName, 
                            username, out reachedMax))
                        {
                            userIsInGroup = true;
                            return;
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        //Trace error
    }
    }); 
    return userIsInGroup;
}
 
private static bool IsUserInADGroup(SPWeb web, string groupName, 
        string username, out bool reachedMax)
{
    // SPUtility call to get principals in the group
    SPPrincipalInfo[] principals = 
            SPUtility.GetPrincipalsInGroup(web, groupName, 500, out reachedMax); 
    // If no principals found then indicate the same
    if (principals == null || principals.Length == 0)
    {
        return false;
    }
    else {
        // Loop through principals
        string upperCaseUserName = username.ToUpper();
        foreach (SPPrincipalInfo principal in principals)
        {
            //TODO: Determine which principal.PrincipalType to ignore
            // Check if the principal is a valid user
            // and if so check to see if it is
            //the one we are looking for
            if (!principal.IsSharePointGroup && principal.PrincipalType 
              != SPPrincipalType.SecurityGroup && 
              principal.DisplayName.ToUpper() != "SYSTEM ACCOUNT")
            {
                // Check if the user matches the user we are looking for
                if (principal.LoginName.ToUpper() == upperCaseUserName)
                {
                    return true;
                }
            }
            // If Principal is a Security Group (AD Group) then recurse through it
            else if (principal.PrincipalType == SPPrincipalType.SecurityGroup)
            {
                // Check for users in the security groups
                if (IsUserInADGroup(web, principal.LoginName, username, out reachedMax))
                {
                    return true;
                }
            }
        }
        return false;
    }
} 
}

Here you will only need to call "IsCurrentUserInRole(string SPGroupName)" method by passing the Sharepoint group name to check whether the current user exists in the specified Sharepoint group and returns true if user exists, otherwise return false.

History

  • 19th May, 2010: Initial post

License

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


Written By
Software Developer (Senior) Tietoenator Software Technologies Private Limited
India India
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
-- There are no messages in this forum --