How to get Auth Token using script when grant type is Authorization code

Rizwan Shaikh
Mega Guru

Hi All,

I have set up a REST Message outbound using OAuth 2.0. 

Accordingly i have set up OAuth Profile

I am able to get the token access token using 'Get OAuth Token' link in REST Outbound. I want to implement this in script. I have been trying the following code. 

var tokenRequest = new sn_auth.GlideOAuthClientRequest();
tokenRequest.setGrantType("authorization_code");

var oAuthClient = new sn_auth.GlideOAuthClient();
var tokenResponse = oAuthClient.requestTokenByRequest("Google Entity profiles", tokenRequest);
gs.info("Error:" + tokenResponse.getErrorMessage());

var token = tokenResponse.getToken(); 
gs.info("AccessToken:" + token.getAccessToken());
gs.info("AccessTokenExpiresIn:" + token.getExpiresIn());
gs.info("RefreshToken:" + token.getRefreshToken());

However it is not working. I am getting the following response

failed to find the oauth entity.
*** Script: Error:failed to find the oauth entity.
*** Script: AccessToken:null
*** Script: AccessTokenExpiresIn:0
*** Script: RefreshToken:null

Please can someone suggest the correct syntax to get Authorization code for grant type as authorization code. I can only find the syntax for grant type password nut not for authorization code.

find_real_file.png

Note: Grant type is not password.

Help is much appreciated. Thanks!

32 REPLIES 32

Instead of profile name, can you check by its sys_id once.

Tried. No Luck. Same Error
Even the syntax says it accepts Entity name

can you update the name to single word and check once.

same error

Hi Rizwan,

From where you are calling that script? Is it from the same scope?

can you check this link:

https://community.servicenow.com/community?id=community_question&sys_id=75f74f2ddb1cdbc01dcaf3231f96...

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader