Get Current User Sys ID: Simple Steps & Code Examples






Mastering Identity: Getting the Current User’s Sys ID and Beyond in ServiceNow



Mastering Identity: Getting the Current User’s Sys ID and Beyond in ServiceNow

Ever found yourself needing to know *who* is currently interacting with your ServiceNow instance? Perhaps you want to personalize an experience, control access to certain features, or log an action taken by a specific individual. In the world of ServiceNow, the answer almost always boils down to one fundamental concept: the Sys ID. This unique identifier is the bedrock of identity, and understanding how to retrieve it for the current user – both client-side and server-side – is a cornerstone skill for any ServiceNow developer or administrator.

But it doesn’t stop there. Once you grasp the current user’s identity, a whole universe of programmatic user and group management opens up. From creating new user accounts and assigning roles to managing group memberships, scripting these actions provides unparalleled automation and control. In this deep dive, we’ll not only equip you with the knowledge to pinpoint the current user’s Sys ID but also guide you through the essential scripts for managing users and groups like a pro.

The Heart of Identity: Understanding the Sys ID

Before we jump into the “how-to,” let’s clarify “what.” A Sys ID in ServiceNow is a 32-character Globally Unique Identifier (GUID). Think of it as the ultimate fingerprint for every record in your database. Every user, every group, every incident, every change request – you name it – has a Sys ID. It’s the primary key that ServiceNow uses internally to uniquely identify records, making it incredibly powerful for scripting, integrations, and lookups.

Why is it so crucial? Because names can change (“John Doe” might become “Jane Smith” after marriage), email addresses can be updated, but a Sys ID remains constant for the lifetime of that record. When you’re building robust, future-proof scripts or integrations, relying on Sys IDs ensures accuracy and stability.

Client-Side Identity: Peeking at the User with g_user.UserID

Imagine you’re building a form, and you want to dynamically show or hide fields, populate values, or trigger alerts based on the user currently looking at the page. This is where client-side scripting comes into play, and your best friend in this scenario is the g_user object.

The g_user object is a global JavaScript object available in client-side scripts (e.g., Client Scripts, UI Policies, UI Pages, Service Portal widgets). It provides a wealth of information about the currently logged-in user, including their name, roles, and, crucially, their Sys ID.

How to Get the User Sys ID Client-Side

To grab the current user’s Sys ID on the client side, you simply use:

g_user.UserID;

This will return the 32-character Sys ID string. For example, it might return something like '6816f79cc0a8016401c5a33be04be441', as indicated in our reference.

Practical Example: Personalizing a Form Alert

Let’s say you want to greet the user with a special message that includes their Sys ID when they load an Incident form:

function onLoad() {
    var currentUserSysId = g_user.UserID;
    var currentUserName = g_user.getFullName(); // Another useful g_user property
    
    if (currentUserSysId) {
        g_form.addInfoMessage('Welcome back, ' + currentUserName + '! Your System ID is: ' + currentUserSysId);
    } else {
        g_form.addErrorMessage('Could not retrieve current user information.');
    }
}

This script, attached as an `onLoad` Client Script to the Incident table, would display an informative message right at the top of the form, showing the user their unique identifier.

Real-World Use Case: Dynamic Form Behavior

Consider a scenario where a specific section of a form (e.g., a “Manager Approval” tab) should only be visible to the user who is designated as the manager of the person submitting the request. You could write a client script that fetches the manager’s Sys ID from the requested_for field and compares it to g_user.UserID. If they match, you then use g_form.setSectionDisplay('manager_approval_section', true); to reveal the section.

Troubleshooting Client-Side Sys ID Issues

  • g_user is undefined: This typically happens if you try to use `g_user` in a server-side script (like a Business Rule or Script Include). Remember, `g_user` is strictly for the client browser context.
  • Incorrect User: Ensure you are actually logged in as the user you expect. Sometimes, developers might switch users but forget to refresh the page where the client script runs.
  • UI Actions/Widgets: For custom UI Actions or Service Portal widgets, ensure your script runs in a context where `g_user` is available. It’s usually present, but double-check if you’re encountering issues.

Interview Relevance: Why g_user is Client-Side

A common interview question might be: “When would you use g_user.UserID versus gs.getUserID()?” The key takeaway here is context. g_user is for anything happening directly in the user’s browser, allowing for immediate feedback and UI manipulation without hitting the server again. It’s faster for interactive elements.

Server-Side Identity: The Authoritative gs.getUserID()

While `g_user` serves client-side needs, what about operations that happen entirely on the server? Think about Business Rules that run before or after a record is saved, Script Includes that perform complex logic, or Scheduled Jobs that execute in the background. For these scenarios, you need the server-side equivalent: gs.getUserID().

The gs object, short for GlideSystem, is a global server-side API that provides utility functions for system-level operations, logging, and, of course, user information.

How to Get the User Sys ID Server-Side

To retrieve the current user’s Sys ID on the server side, use:

gs.getUserID();

This function, like its client-side counterpart, returns the 32-character Sys ID of the user who initiated the server-side script. If the script is running in a background context (like a Scheduled Job) without a direct user interaction, it often returns the Sys ID of the user specified to run the job, or sometimes the “system” user if not explicitly defined.

Practical Example: Logging User Actions in a Business Rule

Let’s say you want to log every time an Incident is updated and record who updated it:

function onAfterUpdate() {
    var currentUserSysId = gs.getUserID();
    var currentUserName = gs.getUserDisplayName(); // Get display name server-side
    
    gs.log('Incident ' + current.number + ' updated by ' + currentUserName + ' (Sys ID: ' + currentUserSysId + ')', 'My Custom Logger');
}

This `onAfter` Business Rule would write a message to the system logs, clearly indicating who made the update, using their Sys ID for precise identification.

Real-World Use Case: Assigning Tasks to the Current User

A common scenario is automatically assigning an Incident or Request Item to the user who submitted it. In an `onBefore` Business Rule or a Workflow script, you could do something like:

current.assigned_to = gs.getUserID();
current.update(); // Only needed if not an onBefore Business Rule

This ensures the task goes directly to the submitter, streamlining the process.

Troubleshooting Server-Side Sys ID Issues

  • gs is undefined: This error will occur if you try to use `gs` in a client-side script. Remember, `gs` is exclusively for server-side execution.
  • Incorrect User in Background Scripts: When debugging Scheduled Jobs or other background processes, be mindful of which user context the script is running under. It might not always be the user you’re currently logged in as, but rather the system user or a specifically configured user. Use `gs.log()` heavily to trace the `gs.getUserID()` value.

Interview Relevance: `gs.getUserID()` vs. `g_user.UserID`

This is a critical distinction for interviews. Emphasize that `gs.getUserID()` is authoritative for all server-side logic, data manipulation, and background processes, where direct user interaction in the browser isn’t the primary concern. It’s also more secure for sensitive operations as it runs outside the potentially manipulable client browser context.

Beyond the Sys ID: User and Group Management Fundamentals

Knowing the current user’s Sys ID is just the beginning. ServiceNow provides robust capabilities for managing users and groups programmatically. This is invaluable for automating onboarding/offboarding, integration with HR systems, or bulk updates.

User Table: sys_user

The foundation of all user-related data in ServiceNow is the sys_user table. This table stores all user profiles, including their names, email addresses, department, roles, and of course, their unique Sys ID. When you look up a user, you’re interacting with this table.

Group Member Table: sys_user_grmember

Users and groups have a many-to-many relationship. A user can belong to multiple groups, and a group can have multiple users. This relationship is managed by the sys_user_grmember table. Each record in this table links a specific user (via their Sys ID) to a specific group (via its Sys ID).

Scripting User Accounts

Creating and managing user accounts manually can be tedious, especially in large organizations. Scripting provides a powerful alternative.

Creating a User Account Using Script

To create a new user, you interact directly with the sys_user table using GlideRecord:

var userGr = new GlideRecord('sys_user');
userGr.initialize(); // Prepares a new, empty record
userGr.username = 'jdoe';
userGr.first_name = 'John'; // Note: field name is 'first_name', not 'firstname'
userGr.last_name = 'Doe';   // Note: field name is 'last_name', not 'lastName'
userGr.email = 'jdoe@example.com';
userGr.insert(); // Saves the new record to the database

gs.info('New user jdoe created with Sys ID: ' + userGr.sys_id); // Log the new user's Sys ID

Explanation:

  • new GlideRecord('sys_user'): Creates a new GlideRecord object for the sys_user table.
  • userGr.initialize(): This is crucial! It prepares a new record for insertion. Without it, you’d be trying to update an existing record (if a query was performed) or nothing at all.
  • userGr.username = 'jdoe': Sets the `username` field. This is typically a unique identifier for login.
  • userGr.first_name = 'John', userGr.last_name = 'Doe', userGr.email = 'jdoe@example.com': Populates other essential fields. Always verify actual field names in the table dictionary if unsure.
  • userGr.insert(): Commits the new record to the database. After this, userGr.sys_id will hold the Sys ID of the newly created user.

Real-World Use Case: Automated User Provisioning

An HR system integrates with ServiceNow. When a new employee joins, an integration (e.g., using REST APIs or a scheduled import) triggers a script like this to automatically create their ServiceNow user account, reducing manual effort and potential errors.

Troubleshooting User Creation

  • Duplicate Username: ServiceNow requires usernames to be unique. If you try to insert a user with an existing username, the insertion will fail. Always include error handling or check for existence first.
  • Missing Required Fields: Some fields might be mandatory (e.g., `user_name`). If you don’t populate them, the `insert()` operation could fail or result in an incomplete record.
  • No Roles: Newly created users won’t have any roles by default. You’ll need to assign them roles separately (covered below).

Scripting Group Accounts

Groups are essential for managing permissions and assignments efficiently. Scripting group creation follows a similar pattern to users.

Creating a Group Using Script

To create a new group, you interact with the sys_user_group table:

var newGr = new GlideRecord('sys_user_group');
newGr.initialize();
newGr.name = 'testing';
newGr.manager = '62826bf03710200044e0bfc8bcbe5df1'; // Sys ID of the manager user
newGr.email = 'testing@tcs.com';
newGr.description = 'Test group for development purposes';
newGr.insert();

gs.info('New group "testing" created with Sys ID: ' + newGr.sys_id);

Explanation:

  • newGr.name = 'testing': Sets the group’s name. This should ideally be unique and descriptive.
  • newGr.manager = '62826bf03710200044e0bfc8bcbe5df1': Assigns a manager to the group. Note that this field expects the Sys ID of a user record, not their username or display name.
  • newGr.email = 'testing@tcs.com': An email address for the group, often used for notifications.

Real-World Use Case: Departmental Group Creation

When a new department is established, an administrator could run a fix script to quickly create the corresponding ServiceNow group, pre-assign a manager, and set a description, saving time over manual creation.

Troubleshooting Group Creation

  • Invalid Manager Sys ID: If the Sys ID provided for `manager` doesn’t correspond to an existing user, the group might still be created, but the manager field will be empty or invalid.
  • Duplicate Group Name: While not strictly enforced to be unique out-of-the-box (unlike usernames), having duplicate group names can lead to confusion. Best practice is to ensure uniqueness.

Managing Roles and Permissions

Roles are fundamental to access control in ServiceNow. They define what a user or group can do. Assigning roles programmatically is a critical automation task.

Adding Roles to Users Using Script

When you assign a role to a user, a record is created in the sys_user_has_role table. You can mimic this with a script:

var userRole = new GlideRecord('sys_user_has_role');
userRole.initialize();
userRole.setValue('user', '62826bf03710200044e0bfc8bcbe5df1'); // Sys ID of the user
userRole.setValue('role', '2831a114c611228501d4ea6c309d626d'); // Sys ID of the role (e.g., 'itil')
userRole.insert();

gs.info('Role assigned to user.');

Explanation:

  • setValue('user', 'SYS_ID'): Links the role assignment to a specific user using their Sys ID.
  • setValue('role', 'SYS_ID'): Links the role assignment to a specific role using its Sys ID. You’d typically find role Sys IDs by navigating to the role record (`sys_user_role.LIST`) and checking its URL or form.

Adding Roles to Groups Using Script

It’s generally a best practice to assign roles to groups rather than individual users. This makes administration easier, as you simply add or remove users from groups, and their roles update automatically. When you assign a role to a group, a record is created in the sys_group_has_role table:

var grpRole = new GlideRecord('sys_group_has_role');
grpRole.initialize();
grpRole.setValue('group', '477a05d153013010b846ddeeff7b1225'); // Sys ID of the group
grpRole.setValue('role', '2831a114c611228501d4ea6c309d626d');  // Sys ID of the role (e.g., 'itil')
grpRole.insert();

gs.info('Role assigned to group.');

Explanation:

  • Similar to user role assignment, but using the `group` field to link to the group’s Sys ID.

Real-World Use Case: Onboarding Role Assignment

A new employee joins the IT team. Instead of manually giving them ITIL, Fulfiller, and other roles, an onboarding workflow can automatically add them to the “ITIL Users” group, and because that group already has the necessary roles, the user gains all permissions instantly.

Troubleshooting Role Assignment

  • Invalid Sys IDs: Ensure the user, group, and role Sys IDs are correct and exist. If any are invalid, the `insert()` will either fail or create a record with empty reference fields.
  • Role Already Assigned: Attempting to assign the same role to a user or group multiple times will simply create redundant records (though ServiceNow handles the effective permissions correctly, it’s not tidy). You might want to add a check before inserting.

Managing Group Members

The sys_user_grmember table is your go-to for adding and removing users from groups.

Adding a Group Member Using Script

To add a user to a group, you create a new record in `sys_user_grmember`:

var grMem = new GlideRecord('sys_user_grmember'); // Correct table name
grMem.initialize();
grMem.user = '62826bf03710200044e0bfc8bcbe5df1';   // Sys ID of the user
grMem.group = '477a05d153013010b846ddeeff7b1225'; // Sys ID of the group
grMem.insert();

gs.info('User added to group.');

Explanation:

  • The `user` field takes the user’s Sys ID.
  • The `group` field takes the group’s Sys ID.

Removing a Group Member Using Script

Removing a user from a group involves finding the specific `sys_user_grmember` record that links them and then deleting it:

var grMem = new GlideRecord('sys_user_grmember');
grMem.addQuery('user', '62826bf03710200044e0bfc8bcbe5df1');   // Query for the user's Sys ID
grMem.addQuery('group', '477a05d153013010b846ddeeff7b1225'); // Query for the group's Sys ID
grMem.query(); // Execute the query

if (grMem.next()) { // Check if a matching record was found
    grMem.deleteRecord(); // Delete the record
    gs.info('User removed from group.');
} else {
    gs.info('User was not a member of the specified group.');
}

Explanation:

  • We use `addQuery()` to precisely locate the record that links *that specific user* to *that specific group*.
  • grMem.query() fetches the record(s).
  • if (grMem.next()) checks if a record matching our query was found.
  • grMem.deleteRecord() removes that single relationship record.

Real-World Use Case: Offboarding Automation

When an employee leaves the company, an offboarding workflow can automatically run scripts to remove them from all their groups, effectively revoking their access to various modules and data within ServiceNow.

Troubleshooting Group Membership

  • Incorrect Sys IDs: Again, ensure the user and group Sys IDs are accurate for both adding and removing.
  • No Record Found for Deletion: If `grMem.next()` returns `false`, it means the user wasn’t a member of that group to begin with, and thus, nothing was deleted. This is expected behavior if the user is not a member.

Checking Group Membership with gs.getUser().isMemberOf()

Beyond simply getting the Sys ID, a very common requirement is to check if the current user belongs to a particular group. ServiceNow provides a super convenient server-side function for this:

gs.getUser().isMemberOf('group name');

This function, used server-side (e.g., in Business Rules, Script Includes, UI Actions condition fields), returns `true` if the current user is a member of the specified group and `false` otherwise.

Practical Example: Limiting UI Action Visibility

Let’s say you have a “Close Incident Permanently” UI action that should only be visible to ITIL Managers. In the “Condition” field of your UI Action, you could use:

gs.getUser().isMemberOf('ITIL Managers');

This ensures the button only appears for users who are part of the ‘ITIL Managers’ group.

Troubleshooting isMemberOf()

  • Case Sensitivity: The group name passed to `isMemberOf()` is case-sensitive. Ensure it exactly matches the name of the group in your instance.
  • Server-Side Only: Like `gs.getUserID()`, `isMemberOf()` is a server-side function. You cannot use it in client scripts.

Interview Relevance: Why `isMemberOf()` is handy

This is a go-to function for security and personalization. Interviewers love to hear about using `isMemberOf()` for UI Action conditions, Business Rule conditions, or script logic to control access and workflow based on roles and groups. It demonstrates an understanding of efficient access control.

Interview Relevance – Connecting the Dots

Understanding these concepts is not just about writing scripts; it’s about demonstrating a holistic grasp of ServiceNow’s identity and access management framework. Here’s how these topics frequently come up in interviews:

  • Client vs. Server-Side: “Explain the difference between g_user.UserID and gs.getUserID() and when you would use each.” (Crucial: Context and performance).
  • Sys IDs: “Why is using Sys IDs a best practice in scripting and integrations?” (Answer: Uniqueness, stability, future-proofing).
  • Programmatic User/Group Management: “How would you automate the onboarding of a new employee, including creating their user account and assigning roles?” (Answer: GlideRecord on `sys_user`, `sys_user_group`, `sys_user_has_role` or `sys_group_has_role`, often via a workflow or integration).
  • Group Membership Checks: “You need to show a specific button on a form only to users in the ‘Finance Department’ group. How would you achieve this?” (Answer: UI Action condition using `gs.getUser().isMemberOf(‘Finance Department’)`).
  • Best Practices: “Should you assign roles directly to users or to groups? Why?” (Answer: To groups, for easier management and scalability).

Troubleshooting Tips – A General Approach

When working with user and group management scripts, inevitably, you’ll hit a snag. Here’s a general troubleshooting checklist:

  • Verify Sys IDs: The most common culprit. Double-check that all user, group, and role Sys IDs used in your scripts are absolutely correct and belong to existing records. A typo in a single character can break everything.
  • Log Everything: Use `gs.log(‘My variable value: ‘ + myVariable);` in server-side scripts and `console.log(‘My variable value: ‘ + myVariable);` or `jslog(‘My variable value: ‘ + myVariable);` in client-side scripts to see what values your variables hold at different stages.
  • Context, Context, Context: Are you trying to use a client-side API (`g_user`) on the server, or vice-versa (`gs`)? Pay close attention to where your script is executing.
  • Initialize GlideRecord: For creating new records, always use `gr.initialize()`. For querying existing ones, ensure you’re using `gr.query()` and `gr.next()`.
  • Check Field Names: Ensure you are using the correct field names for the table you’re interacting with (e.g., `first_name` not `firstname`). The dictionary can be your friend here.
  • Test in Non-Production: Always develop and test these scripts in a sub-production instance first. You don’t want to accidentally create hundreds of test users or delete critical roles in your production environment!
  • Read Error Messages: ServiceNow error messages, especially in the server-side logs, are often quite descriptive. Don’t just gloss over them; they usually point you directly to the problem.

Conclusion

Understanding how to retrieve the current user’s Sys ID, whether from the browser’s perspective with g_user.UserID or from the server’s viewpoint with gs.getUserID(), is a foundational skill in ServiceNow development. It empowers you to create personalized, secure, and dynamic experiences.

Beyond that, mastering the programmatic creation and management of users, groups, and roles using GlideRecord on tables like sys_user, sys_user_group, sys_user_has_role, sys_group_has_role, and sys_user_grmember unlocks immense automation potential. This knowledge not only makes your life as a developer easier but also prepares you to tackle complex identity and access management challenges, making you a more valuable asset in any ServiceNow environment.

So go forth, experiment, and confidently wield the power of user identity and management in ServiceNow!


Scroll to Top