Want to get bearer token to connect to API

cloudv
Tera Contributor

Hi i want to get bearer token by providing client id and client secret to then connect the third party API.

In postman i can provide end point, client_id and client_secret(in headers) and get the following

 

{
    "access_token": "XXXXX",
    "scope": "XXXX",
    "token_type": "Bearer",
    "expires_in": 2500
}
 
I want to replicate the same via a script include or any script  in the servicenow, so far i tried this to test in background script
    var request = new sn_ws.RESTMessageV2();
        request.setEndpoint("https://openapi.service.TEST.net/v1/token");
        request.setHttpMethod("GET");
        request.setQueryParameter("Content-Type", "application/json");
        request.setRequestHeader("client_id","XXXX");
        request.setRequestHeader("client_secret","XXXX");
        var response = request.execute();

        gs.print(response.getBody());
 
But the response i get is 
"requested resource not found"
 
10 REPLIES 10

Hi @Kieran Anson , what type of application registry 

Create an OAuth API endpoint for external clients

Create an OAuth JWT API endpoint for external clients

Connect to a third party OAuth Provider

Configure an OIDC provider to verify ID tokens.

Connect to an OAuth Provider (simplified)

Hi @Kieran Anson , what time of application registry 

Create an OAuth API endpoint for external clients

Create an OAuth JWT API endpoint for external clients

Connect to a third party OAuth Provider

Configure an OIDC provider to verify ID tokens.

Connect to an OAuth Provider (simplified)

Hi @Kieran Anson , what type of application registry 

Eshwar Reddy
Kilo Sage

Hi @cloudv 

Please use below code to get the refresh token
 replace username and password with actual user name and password in code

var req = new sn_ws.RESTMessageV2();
req.setEndpoint("your_endpoint_here");
req.setHttpMethod("POST"); 
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestBody("grant_type=password&username=" + username + "&password=" + password + "&client_id=" + clientid + "&client_secret=" + clientsecret);

var response = req.execute();
if (response.getStatusCode() == 200) {
var parsedResponse = JSON.parse(response.getBody());
var refreshToken = parsedResponse.refresh_token; 
}

 

Please mark this response as Correct and Helpful if it helps you can mark more that one reply as accepted solution

Thanks
Esh

Hi Esh, We don't have password or username we are using client id and client secret