CRM Tip: How to Check Security Role in Plugins – Correct way

Problem Statement:

We often have requirements to perform some action based on certain security role.

For ex., we only want System Administrator to delete particular record, and no one else should delete irrespective of their security access.

There are many ways to achieve this, but many of the times the solution is not foolproof

Incorrect/ Misguided Solution:

Generally developers achieve the above requirement by using plugin with below steps:

  1. Get User ID from the plugin context.
  2. Get all the roles of the user
  3. Loop and check if any of the role name is “System Administrator”.
  4. If Step 3 is true, then allow delete, else restrict delete

This solution works most of the time, but this won’t work if the client is using any other language than English in CRM.

Since role names are customized based on language, the above plugin won’t find any user with the System Administrator name of the role.

Solution:

For language proof solution, we must use the role template lookup on the Role entity.

For OOB security roles, there is a role template GUID which does not change based on environment.

For System Administrator, the Role Template ID is “627090FF-40A3-4053-8790-584EDC5BE201

The following code will get the System Administrator properly.

You can find the sample plugin on my GitHub as well.

public bool HasAdminRole(Guid systemUserId)
{
            Guid AdminRoleTemplateId = new Guid("627090FF-40A3-4053-8790-584EDC5BE201");

            QueryExpression query = new QueryExpression("role");

            query.Criteria.AddCondition("roletemplateid", ConditionOperator.Equal, AdminRoleTemplateId);

            LinkEntity link = query.AddLink("systemuserroles", "roleid", "roleid");

            link.LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, systemUserId);

            return service.RetrieveMultiple(query).Entities.Count > 0;
}

Note:

  1. This can be done for other OOB roles as well like Sales Manager, Sales Person, etc.
  2. For custom roles, the role template Id is empty.
  3. If the custom roles are created by you, then you can used the Role Id (Unique GUID of Role entity) for querying instead of names.

Share Story :

Secured By miniOrange