What is the difference between hasRole() and hasRoleExactly() in servicenow.

Swarnika1
Tera Expert

Can someone please explain me this.

6 REPLIES 6

Ashish04
Tera Contributor

Hi Swarnika,

I will make you understand in simple words.

g_user.hasRole(' ')

1. This method return true if the current logged in user has the role which we have provided in (' ')  otherwise false.

2. It will always returns true if the user has the 'admin' role.

Ex: 1. Consider in the above method if you provide "itil" role and some "abc" user is loggedin to the instance and the user having 'itil' role then it returns true

2. If the user having admin role then also it returns true

 

g_user.hasRoles()  " This method  return true if current logged in user has any single role atleast.

Ex:  Consider in the above method if you provide "itil" ,"service desk" roles and some "xyz" user is loggedin to the instance and the user having either of 'itil' or 'service desk' role then it returns true

 

g_user.hasRoleExactly(‘ ’)  This method return true if current logged in user has role we which have provided in (' ')

Ex:  1. This method return true if the current logged in user has the role which we have provided in (' ')  otherwise false.

2. It will returns false even if the user having 'admin' role.

 

Mark it correct or helpful, if it works.

Regards

Ashish

MerajS765504110
Tera Contributor

In ServiceNow, both g_user.hasRole() and g_user.hasRoleExactly() are used to check if the current user has a specific role, but they differ in how they interpret role inheritance and exact matching:

g_user.hasRole()
Purpose: This method checks if the current user has a specific role, including any inherited roles.
Inheritance: If a user has a role that inherits from other roles, g_user.hasRole() will return true if the user has either the specified role or any role that inherits from it.
Example:
Suppose there is a role admin that inherits the itil role. If you check g_user.hasRole('itil') for a user with the admin role, it will return true because admin includes itil.
g_user.hasRoleExactly()
Purpose: This method checks if the current user has exactly the specified role, without considering role inheritance.
Exact Matching: This method will only return true if the user has the specified role and not because they have a higher or inherited role.
Example:
If you check g_user.hasRoleExactly('itil') for a user with the admin role, it will return false because admin is not exactly itil; it just inherits from it.
Summary
g_user.hasRole(): Returns true if the user has the role or any role that inherits from it.
g_user.hasRoleExactly(): Returns true only if the user has the exact specified role, without considering inheritance.
Use g_user.hasRole() when you want to check if the user has the role or any of its descendants, and use g_user.hasRoleExactly() when you need to check for the specific role without considering inheritance.