how to integrate token in java call

Gotcha—here are quick, copy-paste ways to add an OIDC/JWT Bearer token to Java HTTP calls. Pick the stack you use.


Java 11+ HttpClient

var client = java.net.http.HttpClient.newHttpClient();
String token = "eyJ..."; // put your access token here

var req = java.net.http.HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/resource"))
    .header("Authorization", "Bearer " + token)
    .header("Content-Type", "application/json")
    .POST(java.net.http.HttpRequest.BodyPublishers.ofString("{\"ping\":\"pong\"}"))
    .build();

var res = client.send(req, java.net.http.HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode() + " " + res.body());


OkHttp (popular + simple)

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(chain -> {
        String token = "eyJ..."; // inject per request or from a provider
        Request req = chain.request().newBuilder()
            .addHeader("Authorization", "Bearer " + token)
            .build();
        return chain.proceed(req);
    })
    .build();

Request request = new Request.Builder()
    .url("https://api.example.com/resource")
    .post(RequestBody.create("{\"ping\":\"pong\"}", MediaType.get("application/json")))
    .build();

try (Response resp = client.newCall(request).execute()) {
    System.out.println(resp.code());
}


Apache HttpClient 5

var httpClient = HttpClients.custom()
    .addRequestInterceptorFirst((HttpRequest request, EntityDetails entity, HttpContext ctx) -> {
        request.addHeader("Authorization", "Bearer " + "eyJ...");
    })
    .build();

var post = new HttpPost("https://api.example.com/resource");
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
post.setEntity(new StringEntity("{\"ping\":\"pong\"}", StandardCharsets.UTF_8));

try (var resp = httpClient.execute(post)) {
    System.out.println(resp.getCode());
}


Spring (WebClient) — preferred in Spring Boot

@Bean
WebClient webClient() {
  return WebClient.builder()
      .filter((req, next) -> {
        String token = "eyJ..."; // inject from a bean that caches/refreshes
        ClientRequest r = ClientRequest.from(req)
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + token).build();
        return next.exchange(r);
      })
      .build();
}

// use it
webClient().post().uri("https://api.example.com/resource")
  .contentType(MediaType.APPLICATION_JSON)
  .bodyValue(Map.of("ping","pong"))
  .retrieve().toEntity(String.class).block();


Spring (RestTemplate)

RestTemplate rt = new RestTemplate();
rt.getInterceptors().add((req, body, ex) -> {
  req.getHeaders().setBearerAuth("eyJ...");
  return ex.execute(req, body);
});
ResponseEntity<String> resp = rt.getForEntity("https://api.example.com/resource", String.class);


Feign (OpenFeign)

@Bean
public RequestInterceptor bearerAuth() {
  return template -> template.header("Authorization", "Bearer " + "eyJ...");
}


JAX-WS / SOAP (header example)

SOAP 1.1 often also needs SOAPAction, but the Bearer goes in HTTP headers:

BindingProvider bp = (BindingProvider) port;
Map<String, List<String>> headers = new HashMap<>();
headers.put("Authorization", List.of("Bearer eyJ..."));
bp.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);


Getting the token (Ping/OIDC) in Java (client-credentials)

var client = HttpClient.newHttpClient();
var form = URLEncoder.encode("grant_type","UTF-8") + "=client_credentials" +
           "&" + URLEncoder.encode("client_id","UTF-8") + "=" + URLEncoder.encode(System.getenv("OIDC_CLIENT_ID"),"UTF-8") +
           "&" + URLEncoder.encode("client_secret","UTF-8") + "=" + URLEncoder.encode(System.getenv("OIDC_CLIENT_SECRET"),"UTF-8");

var req = HttpRequest.newBuilder(URI.create("https://idp.example.com/oauth2/token"))
    .header("Content-Type", "application/x-www-form-urlencoded")
    .POST(HttpRequest.BodyPublishers.ofString(form))
    .build();

var res = client.send(req, HttpResponse.BodyHandlers.ofString());
String token = new org.json.JSONObject(res.body()).getString("access_token");


Pro tips (Kong/Ping friendly)

  • Always send Authorization: Bearer <token> (no quotes, single space).
  • Handle 401 by refreshing the token (cache access_token + expires_in).
  • For Cloudflare/ALB in front, ensure they don’t strip Authorization.
  • If you need mTLS as well, add your keystore/truststore to the HTTP client config; the Bearer header stays the same.

If you tell me which client you’re using (Spring WebClient, RestTemplate, OkHttp, Apache, or pure Java 11) and how you obtain tokens (client-credentials vs user flow), I’ll tailor a tiny reusable “TokenProvider” + interceptor for you.

ansible-playbook

---
- name: Delete multiple routes in Kong API Gateway
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Get all routes from Kong
      uri:
        url: "http://localhost:8001/routes"
        method: GET
        return_content: yes
        status_code: 200
      register: kong_routes

    - name: Extract the list of route IDs to delete
      set_fact:
        route_ids: "{{ kong_routes.json.data | map(attribute='id') | list }}"

    - name: Show the route IDs to delete
      debug:
        msg: "Route ID: {{ item }}"
      loop: "{{ route_ids }}"

    - name: Delete each route by its ID
      uri:
        url: "http://localhost:8001/routes/{{ item }}"
        method: DELETE
        status_code: 204
      loop: "{{ route_ids }}"
      when: item is defined
---
- name: Delete multiple services in Kong API Gateway
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Get all services from Kong
      uri:
        url: "http://localhost:8001/services"
        method: GET
        return_content: yes
        status_code: 200
      register: kong_services

    - name: Extract the list of route IDs to delete
      set_fact:
        service_ids: "{{ kong_services.json.data | map(attribute='id') | list }}"

    - name: Show the service IDs to delete
      debug:
        msg: "Service ID: {{ item }}"
      loop: "{{ service_ids }}"

    - name: Delete each service by its ID
      uri:
        url: "http://localhost:8001/services/{{ item }}"
        method: DELETE
        status_code: 204
      loop: "{{ service_ids }}"
      when: item is defined

Kong Service

---
- name: Create Services with Service Paths and Routes in Kong API Gateway
  hosts: localhost
  tasks:

    # Define a list of services, their service paths, and routes
    - name: Define a list of services, service paths, and routes
      set_fact:
        services:
          - { name: service1, service_url: http://example-service1.com:8080/service1, route_name: route1, route_path: /service1 }
          - { name: service2, service_url: http://example-service2.com:8080/service2, route_name: route2, route_path: /service2 }
          - { name: service3, service_url: http://example-service3.com:8080/service3, route_name: route3, route_path: /service3 }

    # Create a Service in Kong for each service defined, including service path
    - name: Create Service in Kong
      uri:
        url: http://localhost:8001/services
        method: POST
        body_format: json
        body:
          name: "{{ item.name }}"
          url: "{{ item.service_url }}"  # Service URL (including the service path)
        status_code: 201
      loop: "{{ services }}"
      register: service_creation

# Create a Route for each Service
    - name: Create Route for the Service
      uri:
        url: http://localhost:8001/routes
        method: POST
        body_format: json
        body:
          service:
            name: "{{ item.name }}"
          name: "{{ item.route_name }}"  # Route name
          paths:
            - "{{ item.route_path }}"  # Route path (external access path)
        status_code: 201
      loop: "{{ services }}"
      when: service_creation is succeeded

    # Optionally verify that services and routes were created
    - name: Verify Service and Route creation
      uri:
        url: http://localhost:8001/services/{{ item.name }}
        method: GET
        status_code: 200
      loop: "{{ services }}"

PING Identity

The error you’re encountering is related to certificate validation and occurs when the system is unable to establish a valid certificate chain to the requested target (usually an external service or API). Specifically, the error message:

SunCertPathBuilderException: unable to find valid certification path to requested target

indicates that the Java application (in this case, Ping Identity) is trying to connect to an HTTPS service, but the service’s SSL/TLS certificate is either:

  • Self-signed, or
  • Issued by a Certificate Authority (CA) that is not trusted by the Java trust store.

Here’s how you can troubleshoot and resolve this issue:

Step 1: Verify the SSL/TLS Certificate

  1. Check the service’s certificate: Use a browser or a tool like openssl to verify the service’s certificate chain:

openssl s_client -connect <hostname>:<port> -showcerts

This will display the certificate chain used by the server. Ensure that the server certificate is valid and that intermediate and root certificates are also included.

  1. Check if the certificate is self-signed: If the service is using a self-signed certificate or a certificate from a CA not included in the default Java trust store, you’ll need to manually trust it.

Step 2: Add the Certificate to the Java Trust Store

You’ll need to import the certificate into the Java trust store so that Java can trust it.

  1. Export the server certificate:
    • Save the certificate to a file using your browser or the openssl command.

For example:

echo | openssl s_client -connect <hostname>:<port> | sed -ne ‘/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p’ > server-cert.pem

  1. Import the certificate into Java’s trust store: Use the keytool command to import the certificate:

sudo keytool -import -alias <alias-name> -file <path-to-cert> -keystore $JAVA_HOME/lib/security/cacerts

Replace:

  1. <alias-name>: A unique alias for the certificate.
  2. <path-to-cert>: The path to the certificate file you saved.

The default password for the Java trust store is usually changeit.

  1. Verify the certificate import: You can verify if the certificate has been successfully imported by listing the contents of the trust store:

sudo keytool -list -keystore $JAVA_HOME/lib/security/cacerts

Step 3: Test the Connection Again

After importing the certificate, restart your application and test the connection again to ensure the error is resolved.

Additional Considerations:

  • Custom Trust Store: If your application is using a custom trust store (not the default Java trust store), ensure that the certificate is added to that trust store instead.
  • CA Certificates: If the certificate is from a trusted CA, ensure that your system has the correct root CA certificates in its trust store.

By importing the certificate into the Java trust store, you should be able to resolve the PKIX path building failed error and establish a successful connection.

Setup services and route in Kong API Gateway

  1. Shell script

<code>

#!/bin/bash

#Set Kong Admin API URL

KONG_ADMIN_URL=”http://localhost:8001&#8243;

#Define an array of services and routes

declare -A services
services=(
[“service11″]=”http://example11.com:8080&#8221;
[“service12″]=”http://example12.com:8080&#8221;
[“service13″]=”http://example13.com:8080&#8221;
)

Define routes corresponding to the services

declare -A routes
routes=(
[“service11″]=”/example11”
[“service12″]=”/example12”
[“service13″]=”/example13”
)

Loop through the services and create them in Kong

for service in “${!services[@]}”; do
# Create each service
echo “Creating service: $service with URL: ${services[$service]}”
curl -i -X POST $KONG_ADMIN_URL/services \
–data name=$service \
–data url=${services[$service]}

# Create a route for each service
echo “Creating route for service: $service with path: ${routes[$service]}”
curl -i -X POST $KONG_ADMIN_URL/routes \
–data paths[]=${routes[$service]} \
–data service.name=$service

# Optionally, add a plugin (e.g., key-auth) to each route

echo “Adding key-auth plugin to route for service: $service”

curl -i -X POST $KONG_ADMIN_URL/routes/${service}/plugins \

–data name=key-auth

done

echo “All services and routes have been configured.

</code>

</code>

  • name: Automate Kong API Mapping for Multiple Services with Different Ports hosts: localhost tasks:
    • name: Define a list of services and routes with different ports set_fact: services: – { name: service6, url: http://service6.com:8086, path: /service6 } – { name: service7, url: http://service7.com:8087, path: /service7 } – { name: service8, url: http://service8.com:8088, path: /service8 } – { name: service9, url: http://service9.com:8089, path: /service9 } – { name: service10, url: http://service10.com:8090, path: /service10 }

    • name: Create a Service in Kong for each service with different ports uri: url: http://localhost:8001/services method: POST body_format: json body: name: “{{ item.name }}” url: “{{ item.url }}” status_code: 201 with_items: “{{ services }}” register: service_creation

    • name: Create a Route for each Service uri: url: http://localhost:8001/routes method: POST body_format: json body: service: name: “{{ item.name }}” paths: – “{{ item.path }}” status_code: 201 with_items: “{{ services }}”

</code>