Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Get OAuth Access Token in Server Side Script

Andrew81
Kilo Contributor

I have a successfully working Outbound REST Message configured with an OAuth2 Application Registered.  This is a normal Azure AD OAuth Application, and i am using Authorization Code flow..  This has all been done using the UI.  I can click (manually) Get OAuth Token and get an OAuth token.  I can then write a Widget with var r = new sn_ws.RESTMessageV2('OAuthAppName', 'MethodName');

This all works wonderfully well etc, my Widgets all work, i can call the API and pull the data back into ServiceNow.

After an hour, my token expires and my Widgets stop working.  This is expected, however, I had assumed that calling  sn_ws.RESTMessageV2() in my Widget server side code would automatically handle all of the authentication again, instead of an administrator manually clicking on "Get OAuth Token" again.

I feel like i have read every possible blog/forum article addressing this issue, but unfortunately, I haven't been able to work out how to re-authenticate whenever someone uses my widget.

Do i really have to write my own oauthclient() code to request authorization and exchange that for a token, when that functionality is already written and hidden behind that "Get OAuth Token" button.

How do i automate this please?

1 ACCEPTED SOLUTION

Vasantharajan N
Tera Sage
Tera Sage

Please refer to the link below where your issue is already addressed

https://community.servicenow.com/community?id=community_question&sys_id=5b544769dbd8dbc01dcaf3231f961937


Thanks & Regards,
Vasanth

View solution in original post

4 REPLIES 4

Vasantharajan N
Tera Sage
Tera Sage

Please refer to the link below where your issue is already addressed

https://community.servicenow.com/community?id=community_question&sys_id=5b544769dbd8dbc01dcaf3231f961937


Thanks & Regards,
Vasanth

Andrew81
Kilo Contributor

For completeness, what i had to do to resolve this issue was add the openid and offline_access scopes to my oath profile.  Without theses scopes, i didn't have a refresh token, and so of course, there was nothing to "refresh" with.

Once the offline_access scope was added, the app registration+RestMessage services handle the refreshing automatically, and i don't have to do anything in code/script.

Alex153
Tera Contributor

Hi @Andrew81 
Can you please share where and how you added openid and offline_access scopes?
Thanks.

can you guide use how you did that?