Help with sending an Oauth token request

simonulbrich
Kilo Contributor

I've been working on an integration with a third party REST api and the required authentication method is Oauth2. I'm able to request get token, using Postman from the third party provider, but I'm having some difficulty getting request correct in ServiceNow. I was able to create a RESTmessage with the correct parameter but would really like to use the builtin Oauth utility. So far I think my problem is that neither the requestTokenByRequest or requestToken funcitons are sending my client credentials in the request header as a base64 encoded basic authentication.. and this is what is expected by the third party authenticator. So far this works:

 

var rm = new sn_ws.RESTMessageV2();
rm.setHttpMethod('POST');
rm.setEndpoint("https://some_url.com/restapi/oauth/token");
rm.setBasicAuth('client_id', 'client_secret');
rm.setRequestHeader('content-type','application/x-www-form-urlencoded');
rm.setRequestHeader('Accept','application/json');
rm.setRequestBody("username=me&password=nothing_to_see_here&grant_type=password");
var response = rm.execute();
var body = response.getBody();
gs.print(body);

 

but this won't:

var tokenRequest = new sn_auth.GlideOAuthClientRequest();
tokenRequest.setParameter('authorization','Basic client_id:client_secret_base_64_encoded');
tokenRequest.setGrantType('password');
tokenRequest.setUserName('me');
tokenRequest.setPassword('nothing_to_see_here');
tokenRequest.setScope(null);
var oAuthClient = new sn_auth.GlideOAuthClient();
gs.print(tokenRequest.getParameter('authorization'));
var tokenResponse = oAuthClient.requestTokenByRequest('Oauth_app_registry_name', tokenRequest);

or this:

var oAuthClient = new GlideOAuthClient();
var params ={grant_type:'password', username:'me', password:'nothing_to_see_here'};
var json =new JSON();
var text = json.encode(params);
var tokenResponse = oAuthClient.requestToken('Oauth_app_registry_name', text);

 

Any Ideas?

4 REPLIES 4

Warren10
Kilo Explorer

Hi Simon, what is the error you get?  I'm also facing a similar issue and have just posted my own question.

Mahendra RC
Mega Sage

Hi Simon,

Are you getting any error for the part that is not working. Could you please let me know what error you are getting.

Thanks

simonulbrich
Kilo Contributor

Hi Mahendra,

 

Here is the error I get when running the two failing code blocks:

 

OAuthProblemException{error='invalid_client', description='Client authentication is required', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}

Ronald Chik
Tera Contributor

Hi Simon,

Do you have any solution at the end? I am facing exactly the same problem.