Simulate login with just a generated token?

hoathong99
Tera Contributor

I just applied intern for the job, I was asked to make a QR login so user can just login by scan the code. there are no username,password to input.
-I made a table and page for admin to choose a user and generate a single use token with expire date for it and a page to handle validate the token.
-The script can already validate the token and get the user but I don't know what to simulate logging in. I tried both gs getSession loadUserByID and gs getSession impersonate but they seems to like mimic user to do task in the script but not setting current session to that of the target user.
Please suggest me ideas or way to do it

 
1 REPLY 1

Community Alums
Not applicable

hi @hoathong99 ,

  • gs.getSession().impersonate() lets your script act like the user, but it does not change the actual web session of the browser.

  • So the browser session still belongs to the original user or anonymous session.


How to do real login with token in ServiceNow:

  1. Use the ServiceNow REST API or Authentication API:

    • Normally, ServiceNow uses username/password or SSO to log users in.

    • But you can create a custom authentication handler that checks your token.

    • When user scans QR, the token is sent to your custom login URL.

    • If token is valid, you programmatically create a session for that user.

  2. Use GlideSession APIs for creating sessions on server side:

    • Server scripts can create sessions but it’s tricky because ServiceNow controls session cookies in the browser.

    • You cannot simply assign current user in script and expect the browser session to switch.

  3. Recommended approach - Redirect with a token parameter and handle login in a UI Script:

    • After token validation, redirect the user to a URL like /login_redirect.do?sysparm_token=xxxx

    • Create a UI Script or Script Include that processes this token, validates it, and then logs the user in by setting gs.getSession().setCurrentUser()

    • But again, this may not fully work for the web session unless you use an authentication mechanism.

  4. Best practice: Use OAuth or SSO style flow with your token as a one-time code:

    • ServiceNow supports OAuth and SAML.

    • You can create an OAuth token based on your single-use token.

    • Then, redirect user to login with that OAuth token.

  5. Simple workaround using Impersonation and Redirect:

    • Use impersonation server side, then redirect user to the homepage.

    • The user will see the impersonated session.

    • But the user might have to confirm or it’s visible in UI.