Determining if a user has a particular security role

Introduction

Consider the situation where a field on a Dynamics 365 form needs to be either shown or hidden based on whether the logged in user has a particular security role. This is usually achieved by calling the following client Api.

let userSettings = Xrm.Utility.getGlobalContext().userSettings.securityRoles

This api returns the display name of each of the security role assigned to the user (user roles) and any security roles assigned to the team (team roles) that the user is associated with. For example,

  • name = ‘Record Officer’
  • id = 21ad683f-1b06-4a05-b8f3-9c00da-7bc91b

So, if the requirement was to hide a certain field on a form for a ‘Record Officer’, the logic would iterate thru the logged in user’s retrieved security roles. If one of those roles had the id = 21ad683f-1b06-4a05-b8f3-9c00da-7bc91b, it would then hide that particular field on the form

This approach works fine in most circumstances, however…

An issue with this approach

Figure 1

Consider the situation where a TypeScript developer is writing code for the case where the logged in user is residing in the ‘Services’ child business unit (Figure 1). When the developer is working in their Dev 1 environment (Figure 2), they would hardcode the ‘Record Officer’ role to an id of 21ad683f-1b06-4a05-b8f3-9c00da-7bc91b. However, when the code is moved to Sit 1 (Figure 3), the id is different and thus the TypeScript code would stop working

Figure 2
Figure 3

Solution

Referring to Figures 2 & 3, when moving between environments, the parent business unit id doesn’t change. Thus, this is the id that needs to be referenced in the typescript code. This code (Figure 4) would be used in place of Xrm.Utility.getGlobalContext().userSettings.securityRoles

Figure 4

References

https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings

https://community.dynamics.com/blogs/post/?postid=fdd9d3bc-9f66-41c6-be40-4a1258724ef4