package org.aktin.broker.client2.auth;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.keycloak.authorization.client.AuthzClient;

public class OpenIdAuthentication extends HttpAuthorizationBearerAuth {

  private String apiKey;

  public OpenIdAuthentication(String apiKey) {
    this.apiKey = apiKey;
  }

  @Override
  protected String getBearerToken() throws IOException {
    try (InputStream in = Files.newInputStream(Paths.get("keycloak.json"))) {
      return AuthzClient.create(in).obtainAccessToken().getToken();
    } catch (IOException e) {
			System.err.println("Unable to read keycloak.json: " + e.getMessage());
			throw(e);
		}
  }

}

@@ -203,232 +203,771 @@
 nt;%0A
-%0Apublic class OpenIdAuthentication extends HttpAuthorizationBearerAuth %7B%0A%0A  private String apiKey;%0A%0A  public OpenIdAuthentication(String apiKey) %7B%0A    this.apiKey = apiKey;%0A  %7D%0A%0A  @Override%0A  protected String getBearerToken(
+import org.keycloak.representations.AccessTokenResponse;%0A%0A/**%0A * OpenID authentication via Keycloak client.%0A * Use e.g. by passing the file %7B@code keycloak.json%7D to %0A * constructor %7B@link #OpenIdAuthentication(String)%7D %0A *%0A */%0Apublic class OpenIdAuthentication extends HttpAuthorizationBearerAuth %7B%0A%09private AuthzClient client;%0A%09private AccessTokenResponse resp;%0A%09private long expirationTimestamp;%0A%0A%09private void checkAndRefreshToken() %7B%0A%09%09long now = System.currentTimeMillis();%0A%09%09if( expirationTimestamp == 0 %7C%7C expirationTimestamp %3C now ) %7B%0A%09%09%09// obtain new token%0A%09%09%09resp = client.obtainAccessToken();%0A%09%09%09// resp.expiresIn is seconds???%0A%09%09%09expirationTimestamp = now + 1000*resp.getExpiresIn();%09%09%0A%09%09%7D%0A%09%7D%0A%09public OpenIdAuthentication(String keycloakJsonConfigPath
 ) th
@@ -985,20 +985,18 @@
 ption %7B%0A
-    
+%09%09
 try (Inp
@@ -1044,17 +1044,16 @@
 get(
-%22
 keycloak
 .jso
@@ -1052,101 +1052,157 @@
 loak
-.json%22))) %7B%0A      return AuthzClient.create(in).obtainAccessToken().getToken();%0A    %7D catch (
+JsonConfigPath))) %7B%0A%09%09%09this.client = AuthzClient.create(in);%0A%09%09%09checkAndRefreshToken();%0A%09%09%7D%0A%09%7D%0A%0A%09@Override%0A%09protected String getBearerToken() throws 
 IOEx
@@ -1212,107 +1212,64 @@
 tion
- e)
  %7B%0A%09%09
-%09System.err.println(%22Unable to read keycloak.json: %22 + e.getMessage());%0A%09%09%09throw(e);%0A%09%09%7D%0A  
+checkAndRefreshToken();%0A%09%09return resp.getToken();%0A%09
 %7D%0A%0A%7D

refresh token only if needed, e.g. because expired