We will see how to check what Security Roles are available to logged in User and do Custom Logic in Dynamics 365.
We come across scenarios where a ribbon button should be show/hide based on logged in user’s security role or enable/disable some functionality based on logged in user’s security role.

This has been achieved with a JavaScript Web Resource in different patterns.
Following commands return Security Roles (GUID),

Security Roles

Returns Array of Security Roles (Labels) assigned to logged in User.

Security Roles 1

Once we have list roles, loop them and check for the desired security role and return a flag to perform the required operation.

var flag = false;
          for(i=0; i<roles.length; i++) {
                 var name = roles[i].name;
                 if(name == “System Administrator”)
                 flag = true;   }

Consider a scenario, where we have a HTML web resource being used for a custom functionality and we must restrict/allow a piece of functionality to set of users who have a desired security role.

Security Roles 1

The above used command to get Security Roles names will not work in a HTML web resource.

Here we have to first get the list of Security Roles (GUID) available to the logged in User using following command which return an array with assigned security role’s GUIDs.

Security Roles 2

Once we have list of GUIDs available we have loop each GUID and using Retrieve Single have to fetch the Security Role Label.

Here we have a getrole function in which we have to use Retrieve Single and return security role label.

function getrole(roleid) {
       var name;
       var req = new XMLHttpRequest();“GET”, Xrm.Utility.getGlobalContext().getClientUrl() + “/api/data/v9.1/roles(” + roleid +         “)? $select=name”, false);
       req.setRequestHeader(“OData-MaxVersion”, “4.0”);
       req.setRequestHeader(“OData-Version”, “4.0”);
       req.setRequestHeader(“Accept”, “application/json”);
       req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
       req.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);
       req.onreadystatechange = function() {
             if (this.readyState === 4) {
                  req.onreadystatechange = null;
                  if (this.status === 200) {
                        var result = JSON.parse(this.response);
                        name = result[“name”];
              } else {
         return name;

Use the returned security role in the loop of security roles.

var flag = false;

var SecurityRoles = [];
            for (var i = 0; i < roles.length; i++) {
                SecurityRoles[i] = getrole(roles[i]);
                if (SecurityRoles[i] ==  “System Administrator”)
                flag = true;

If the flag returns true then perform the required functionality.









Leave a Reply