Click here to Skip to main content
Click here to Skip to main content

Check Whether User Exists in Active Directory

By , 19 May 2010
Rate this:
Please Sign up or sign in to vote.

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

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)

About the Author

ManasMoharana
Software Developer (Senior) Tietoenator Software Technologies Private Limited
India India
Manas Ranjan Moharana is a senior software Engineer, and has been in the industry since April 2005. He has experience in MOSS 2007,MOSS 2010,Commerce Server 2009, ASP.NET, C#, Windows Forms, Visual Basic,, JavaScript, and HTML.

Comments and Discussions

 
QuestionAD Authentication Pinmembercesare.cogliandro@teletu.it1-Jul-13 22:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 19 May 2010
Article Copyright 2010 by ManasMoharana
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid