Granting authorization to the API with Java

Heading over to Java, you will need to grant authorization to the API. Begin by creating a new Maven project and configure your pom.xml file, by doping the following.

New Maven project

  • Select the latest version.

Latest version

  • Select Maven and copy the displayed dependency.

Dependency

  • Go back to your IDE and paste that dependency into your pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>JavaClient</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

Troubleshooting

Case 1. The text within the dependency is red

Step 1: Check that you have Maven installed.

  • Go to Settings, find Plugins and make sure Maven is under the installed build tools.
  • Go to Build, Execution, Deployment > Build Tools > Maven, if the Use settings from .mvn/maven.config box is selected, deselect it.

Step 2: Create a new Java Class called FetchToken.

  • Import these libraries.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import org.json.JSONObject;
  • Within the public class FetchToken, create the TOKEN_URL, CLIENT_ID and CLIENT_SECRET variables (fill in the fields with your own values).
public class FetchToken {
private static final String TOKEN_URL = "http://your-openiam-instance/idp/oauth2/token";
private static final String CLIENT_ID = "your client id";
private static final String CLIENT_SECRET = "your secret id";
  • Create the function public static String getToken() for obtaining an auth token.
public static String getToken() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
String authHeader = Base64.getEncoder().encodeToString((CLIENT_ID + ":" + CLIENT_SECRET).getBytes());
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(TOKEN_URL))
.header("Authorization", "Basic " + authHeader)
.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) {
JSONObject jsonResponse = new JSONObject(response.body());
String accessToken = jsonResponse.optString("access_token", null);
if (accessToken == null) {
System.out.println("Error: Access token not found in the response");
}
return accessToken;
} else {
System.out.printf("Error: %d, %s%n", response.statusCode(), response.body());
return null;
}
}
  • In main, create a String accessToken that will call getToken() and print it out. Note: printing out the token is not necessary but will confirm that your program is working as intended.
public static void main(String[] args) {
try {
String accessToken = getToken();
if (accessToken != null) {
System.out.println("Access Token: " + accessToken);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}

An example of the full code is given below.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import org.json.JSONObject;
public class FetchToken {
private static final String TOKEN_URL = "http://localhost.openiam.com:8080/idp/oauth2/token";
private static final String CLIENT_ID = "89CF108C07274048AE42DEBD251F2ABA";
private static final String CLIENT_SECRET = "fdc3f1658731bd812105c841e07a8ceece72d553089d5d7e8e19e101b3f3652c";
public static void main(String[] args) {
try {
String accessToken = getToken();
if (accessToken != null) {
System.out.println("Access Token: " + accessToken);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public static String getToken() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
String authHeader = Base64.getEncoder().encodeToString((CLIENT_ID + ":" + CLIENT_SECRET).getBytes());
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(TOKEN_URL))
.header("Authorization", "Basic " + authHeader)
.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) {
JSONObject jsonResponse = new JSONObject(response.body());
String accessToken = jsonResponse.optString("access_token", null);
if (accessToken == null) {
System.out.println("Error: Access token not found in the response");
}
return accessToken;
} else {
System.out.printf("Error: %d, %s%n", response.statusCode(), response.body());
return null;
}
}
}
After running FetchToken, if working properly, the output should be similar to this:
Access Token: 9Hc58KWwqKwPmlDXeeHj6kBwp3xswhxA3XLB91FoYtGpAi1kASi.TJ-IETfTedAfiwyUMsu.gOpV4e4wB-kub-