Tuesday, October 16, 2007

LDAP and Sitecore user/role mapping


Sometimes you may need certain users imported from Active Directory through the LDAP module to be associated with some Sitecore-native roles such as default Sitecore 5.3 Client Roles.

In order to accomplish this, you need to customize the LDAPDomain class that is associated with the domain definitions in web.config.

Just create your own class that will inherit from Sitecore.Modules.LDAP.LDAPDomain:

public class LDAPDomain : Sitecore.Modules.LDAP.LDAPDomain
  {
     public LDAPDomain(string domainName, string databaseName)
        : base(domainName, databaseName)
     {

     }

}

Then override the Login method that will call the base implementation of the Login method and post process the AD user:

public override Sitecore.SecurityModel.DomainAccessResult Login(string userName, string password)
       {
           DomainAccessResult loginResult = base.Login(userName, password);
           if (loginResult.Success)
           {
               UserItem user = this.GetUser(userName);
               if (user["Fromldap"] == "1")
               {
                   // Optional: Get the Role that is already imported from AD
                   RoleItem techSupportRole = Sitecore.Context.Domain.GetRole("Technical Support");

                   // Optional: if the role is found and the user is a member of this role
                   if (techSupportRole != null && user.Roles.Contains(techSupportRole.ID))
                   {
                       user.BeginEdit();

                       // getting Sitecore Client Authoring Role
                       RoleItem clientAuthRole = Sitecore.Context.Domain.GetRole(ID.Parse("{DE4E5C04-F820-4406-AEB9-C76144F7D808}"));
                       // Getting Sitecore Maintaining Role
                       RoleItem clientMaintRole = Sitecore.Context.Domain.GetRole(ID.Parse("{E2036D1D-2828-42B9-8D41-1AD2F247C256}"));

                       // assigne the Sitecore Client Authoring Role to the user
                       if (clientAuthRole != null)
                       {
                           user.Roles.AddRole(clientAuthRole.ID);
                       }

                       // assigne the Sitecore Maintaining Role to the user
                       if (clientMaintRole != null)
                       {
                           user.Roles.AddRole(clientMaintRole.ID);
                       }

                       user.EndEdit();
                   }
               }
           }
           return loginResult;
       }

The code is pretty easy and self-explanatory.

Instead of hard-coding the role IDs, you can of course create a Sitecore item that will contain the role mappings, so this logic can read it and apply the rules on the fly.

Thanks to Ivan Sharamok for the idea.

0 comments: