Can someone please give me code sample to call a REST API from a Rule using client credential authentication?
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class OAuthClientCredentialsExample {
private static final String TOKEN_URL = "https://your-auth-server.com/oauth/token";
private static final String CLIENT_ID = "your-client-id";
private static final String CLIENT_SECRET = "your-client-secret";
private static final String API_URL = "https://api.yourservice.com/resource";
public static void main(String[] args) throws Exception {
// 1. Get the access token
String accessToken = getAccessToken(CLIENT_ID, CLIENT_SECRET);
// 2. Use the access token to make an API request
makeApiRequest(accessToken);
}
private static String getAccessToken(String clientId, String clientSecret) throws Exception {
HttpClient client = HttpClient.newHttpClient();
String auth = clientId + ":" + clientSecret;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(TOKEN_URL))
.header("Authorization", "Basic " + encodedAuth)
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString("grant_type=client_credentials"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
// Extract access token from the response
String responseBody = response.body();
// Assuming the response is in JSON format and contains the access token
// You might want to use a JSON library to parse the response properly
String accessToken = extractAccessToken(responseBody);
return accessToken;
} else {
throw new RuntimeException("Failed to get access token: " + response.body());
}
}
private static String extractAccessToken(String responseBody) {
// Simple parsing for the sake of example. In real scenarios, use a JSON library like Jackson or Gson
int start = responseBody.indexOf("\"access_token\":\"") + 16;
int end = responseBody.indexOf("\"", start);
return responseBody.substring(start, end);
}
private static void makeApiRequest(String accessToken) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(API_URL))
.header("Authorization", "Bearer " + accessToken)
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
System.out.println("API Response: " + response.body());
} else {
throw new RuntimeException("Failed to call API: " + response.body());
}
}
}
Hi @pg_bgen,
Please find the sample code. If the ask is with respect to some specific rule type, then let us know the same so that accordingly suggestion can be given.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import org.json.JSONObject;
public class RestApiClient {
public static void main(String[] args) {
try {
// Client credentials
String clientId = "your_client_id";
String clientSecret = "your_client_secret";
String tokenUrl = "https://auth.example.com/oauth2/token";
String apiUrl = "https://api.example.com/data";
// Obtain access token
String accessToken = getAccessToken(clientId, clientSecret, tokenUrl);
// Call REST API with access token
callApiWithAccessToken(apiUrl, accessToken);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getAccessToken(String clientId, String clientSecret, String tokenUrl) throws Exception {
// Create URL object
URL url = new URL(tokenUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to POST
connection.setRequestMethod("POST");
// Set request headers
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()));
// Enable input and output streams
connection.setDoOutput(true);
// Set request body
String requestBody = "grant_type=client_credentials";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = requestBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Get the response code
int responseCode = connection.getResponseCode();
// Check if the request was successful
if (responseCode == HttpURLConnection.HTTP_OK) {
// Read the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Parse the response to get the access token
JSONObject jsonResponse = new JSONObject(response.toString());
return jsonResponse.getString("access_token");
} else {
throw new RuntimeException("Failed to obtain access token. Response Code: " + responseCode);
}
}
private static void callApiWithAccessToken(String apiUrl, String accessToken) throws Exception {
// Create URL object
URL url = new URL(apiUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Set request headers
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Accept", "application/json");
// Get the response code
int responseCode = connection.getResponseCode();
// Check if the request was successful
if (responseCode == HttpURLConnection.HTTP_OK) {
// Read the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print the response
System.out.println("Response: " + response.toString());
} else {
System.out.println("GET request failed. Response Code: " + responseCode);
}
// Disconnect the connection
connection.disconnect();
}
}
Thanks
This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.