Are you tired of Sitecore Security not working the way you would expect when adding Active Directory groups and accounts to Sitecore Roles?
I’ve developed a little class that takes care of that for you.
Here is the code, it’s well documented in-line so following the logic shouldn’t be an issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Security = Sitecore.Security;
using Sitecore.Diagnostics;
using Sitecore.Security;
using Sitecore.Security.Accounts;
using System.Web;
using site = Sitecore;
using Sitecore.Security.Domains;
namespace YourCompany.WebHive.Sitecore
{
public class SwitchingRoleProvider : Security.SwitchingRoleProvider
{
public override bool IsUserInRole(string userName, string roleName)
{
Assert.ArgumentNotNull(roleName, "roleName");
RoleProviderWrapper wrapper = this.Wrappers.GetWrapper(roleName);
try
{
//Do this only for SQLRoleProvider as it's not possible to add
//roles / accounts outside of AD to AD groups.
if (wrapper.Provider is System.Web.Security.SqlRoleProvider)
{
//Get all members of the Role passed.
IEnumerable accts = RolesInRolesManager.GetRoleMembers(Security.Accounts.Role.FromName(roleName),
false);
//If there are any member roles in other domains possibly other provider types.
if (accts.Count() > 0)
{
//Go through each account
foreach (Account account in accts)
{
//Cast to user.
User usr = account as User;
//If the account IS a user
if (usr != null)
{
//Does the user equal the passed userName?
if (userName.Equals(usr.Name))
return true;
}
else //If account IS NOT a user
{
//Cast to Role
Role role = account as Role;
//If the account IS a role
if (role != null)
//use base logic
return base.IsUserInRole(userName, role.Name);
}
}
}
else //If there are no roles outside of the domain of the role passed (roleName)
return false;
}
else
//If the role provider for the passed role (roleName) is not of type SqlRoleProvider,
//use the base functionality.
return base.IsUserInRole(userName, roleName);
}
catch (Exception ex)
{
//Log any error.
site.Diagnostics.Log.Error(
String.Format("Error trying to find user \"{0}\" in role \"{1}\"",
userName, roleName),
ex, this);
}
//Catch all -- if exception.
return false;
}
}
}
Once you’ve created the class and built the DLL you’ll need to change the web.config
You’ll want to replace this line:
Wtih this one, updated with the new Switching Provider:
This only works when adding AD users / groups ONE 1 level deep, this is for obvious performance reasons. If you want to go deeper in the tree, I’d change the logic to run recursively instead of using the base method.