gs.getSession().impersonate() in scoped application?

vks
Kilo Expert

I have a ServiceNow Application which is programatically called from a Windows Application via Processor. Windows Application sends a username and token to impersonate. In global application I used to do this quite easily by validating the username and token and calling this api:

gs.getSession().impersonate(<user_sys_id>);

Now that Scoped GlideSession doesn't expose impersonate, how could I achieve this?

Thanks,

Vipin

12 REPLIES 12

The SN Nerd
Giga Sage
Giga Sage

What you are currently doing isn't terribly secure, you can probably understand why ServiceNow disallow this API call in scoped applications.



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

anthony_m
Kilo Contributor

Hi Vipin



Did you ever solve this?


Since the API is not available, there is no way to call that line of code.


It is, however, possible to run code as any given user in the background by the following method:



  • Extend the Scheduled Job table to a new Scoped Table
    • This is so your code can be packaged as part of your app
  • Put the code you want to run into the 'Script' field
  • Add the user you want to the 'run_as' field
  • Use the code below


var tablename = 'your_scoped_app_table_name';
var gr = new GlideRecordUtil.getGR(tablename,'sys_id_of_gr_with_code_and_user');


gs.execute(gr);



And you can run code as any user in a Scoped Application (in the background)


If you want to catch the completion of the code, you will need to throw an event similarly.



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

Prasad Dhule
Tera Contributor

Hi Vipin,



You can create a global script include which is accessible to all scopes and imperssonate from the there.



var Impersonator = Class.create();


Impersonator.prototype = {


      initialize: function() {


      },


        impersonateUser : function(impersonate_to){


              gs.info("Impersonated to "+impersonate_to);


              return gs.getSession().impersonate(impersonate_to);


      },


      type: 'Impersonator'


}




// From scoped application


var impersonator =   new global.Impersonator().impersonateUser('user_id');


This would work, but then you have a global dependency, and the code cannot be shipped / included as part of your scoped Application.



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022