Show all Sitecore Active Directory users

I manage a Sitecore installation that’s integrated with an enterprise Active Directory.

We have over 11,000 accounts in our Active Directory. I needed a list of the Sitecore users, who are only a small percentage of the 11,000.

We have nothing in Active Directory that sets them apart, like group membership.

We architected our solution so that users are never assigned directly to items; users are members of Sitecore roles, and we assign Sitecore roles to items. All I have to do is rifle through all my Sitecore roles.

So how do I find my users? It took a little C#. Here’s the core code:

var roles = Sitecore.Security.Domains.Domain.GetDomain("sitecore").GetRoles();
foreach (var role in roles)
{
    foreach(var roleMember in Sitecore.Security.Accounts.RolesInRolesManager.GetRoleMembers(role, false))
    {
        if (roleMember.AccountType == AccountType.User)
        {
            var userObject = Sitecore.Security.Accounts.User.FromName(roleMember.Name, false);
 
            // only adding SMU domain users
            if (userObject.Domain.Name == "myActiveDirectoryDomain")
                AddUserToList(userObject);
        }
    }
}

This gets all Sitecore domain groups and extracts all users who are a member of my corporate domain. Of course,¬†you’ll replace¬†myActiveDirectoryDomain with your own domain name.

I created a separate AddUserToList method to handle adding these items to a Dictionary:

private void AddUserToList(User user)
{
    if (!_users.ContainsKey(user.Name))
    {
        _users.Add(user.Name,user);
    }
}

After the core code runs, you’ll need to code your own stuff to spit out what’s in the dictionary.

Here’s what I used:

foreach(var user in _users)
{
    var row = new TableRow();
    OutputTable.Rows.Add(row);
 
    row.Cells.Add(new TableCell { Text = user.Value.Profile.UserName });
    row.Cells.Add(new TableCell { Text = user.Value.Profile.FullName });
    row.Cells.Add(new TableCell { Text = user.Value.Profile.Email });
 
    if (user.Value.Profile.FullName.Length == 0)
    {
        row.CssClass = "alert";
    }
 
    var rolesCell = new TableCell();
 
    foreach (var role in RolesInRolesManager.GetRolesForUser(user.Value, false))
    {
        if (role.Domain.Name == "sitecore")
        {
            rolesCell.Text += "
 " + role.Name;
        }
    }
 
    rolesCell.Text = rolesCell.Text.Substring(7);
    row.Cells.Add(rolesCell);
}

Note that I already had a Table named OutputTable on my ASPX page.

Tadaa! The result is a list of all my domain members who are Sitecore users.