We will learn to get user security roles in Dynamics 365 using JavaScript. Before we start, make sure to subscribe to CRM Crate so that you stay up-to-date in field of Dynamics 365 CRM.
Why do we need to get user security roles in Dynamics 365?
Consider a scenario where we need to perform a dedicated set of actions / operations based upon the current user’s security role. We can achieve this requirement with help of getGlobalContext.userSettings client API.
Using getGlobalContext.userSettings client API in JavaScript –
This client API returns the information about the current user settings in form of objects.
Xrm.Utility.getGlobalContext().userSettings
The userSettings object provides following properties and a method.
JavaScript snippet for retrieving user security role –
Below is the JavaScript code deployed in the “OnLoad” event of Dynamics 365 form.
//CRM Crate - JavaScript Snippet
function CallMethod (executionContext) {
//Retrieving Global Context.
var context = Xrm.Utility.getGlobalContext();
//Store Security Roles
var loggedUserRoles = context.userSettings.roles;
//Looping Through User's Security Roles.
loggedUserRoles.forEach(function hasRoleName(item, index) {
//Printing User Security Roles.
console.log("Security Role = " +item.name);
});
}
Validating the JavaScript snippet execution in the Dynamics 365 form –
- Open the Dynamics 365 CRM, deploy the above code in the “OnLoad” event of the entity form.
- Save and publish the deployed changes.
- Navigate to the Dynamics 365 record and open the console to verify the retrieved security roles.
Thus we learned to retrieve user security roles in Dynamics 365 using JavaScript.