


Dynamics 365: Check if the current user has specific role
You often need to check in your client script if the current user has a special security role, for instance in a custom rule as part of a ribbon enable rule.
Here is a short code snippet that can be used for checking if the current user contains the security role with a specific name:
Javascript:
function hasCurrentUserRole(roleName){ let hasRole = false; let roles = Xrm.Utility.getGlobalContext().userSettings.roles; roles.forEach(x => { if (x.name === roleName) { hasRole = true; return; } }); return hasRole; }
TypeScript:
static hasCurrentUserRole(roleName: string): boolean { let hasRole = false; let roles = Xrm.Utility.getGlobalContext().userSettings.roles; roles.forEach(x => { if (x.name === roleName) { hasRole = true; return; } }); return hasRole; }
In case you want to check the security role by its id, you can do it as follows. Keep in mind that the id’s from the roles collection contains the curly braces:
function hasCurrentUserRole(roleId){ let hasRole = false; let roles = Xrm.Utility.getGlobalContext().userSettings.roles; roles.forEach(x => { if (x.id === roleId) { hasRole = true; return; } }); return hasRole; }
Here are some links for more information: