Want to get bearer token to connect to API
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-01-2024 05:54 AM - edited 10-01-2024 05:57 AM
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
"requested resource not found"
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-01-2024 09:10 AM
Apologies for the misunderstanding! Here’s the response written in a reply form:
---
Hi,
The issue seems to be with how you're making the request to obtain the bearer token. There are a few things that need adjustment:
### 1. **HTTP Method**:
The API you're connecting to likely requires a **POST** request, not a **GET** request, for token generation. Typically, OAuth 2.0 token requests are made using **POST**.
### 2. **Parameters in the Body**:
Instead of sending the `client_id` and `client_secret` in the headers, you should include them in the **request body** as form parameters. You should also pass the `grant_type` parameter, which for this type of request is usually set to `client_credentials`.
### 3. **Content-Type Header**:
The `Content-Type` should be set as a **header**, not a query parameter, and it should be `application/x-www-form-urlencoded` since this is the standard for OAuth token requests.
### Here's a corrected version of your script:
```javascript
var request = new sn_ws.RESTMessageV2();
request.setEndpoint("https://openapi.service.TEST.net/v1/token");
request.setHttpMethod("POST");
// Set the appropriate content type for form data
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Pass the client_id, client_secret, and grant_type in the request body
request.setRequestBody("client_id=XXXX&client_secret=XXXX&grant_type=client_credentials");
try {
var response = request.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.print("HTTP Status: " + httpStatus);
gs.print("Response Body: " + responseBody);
} catch (ex) {
var message = ex.getMessage();
gs.print("Error: " + message);
}
```
### Changes:
- Changed the method from **GET** to **POST**.
- Moved `client_id` and `client_secret` to the **request body** and included `grant_type=client_credentials`.
- Set the **Content-Type** header correctly.
Once you run this script, it should return the token as expected. Let me know if you need any further assistance!
Best regards,
Raja