88 lines
2.2 KiB
Java
88 lines
2.2 KiB
Java
package org.gcube.common.security.secrets;
|
|
|
|
import java.net.URL;
|
|
import java.util.Map;
|
|
|
|
import org.gcube.common.keycloak.KeycloakClient;
|
|
import org.gcube.common.keycloak.KeycloakClientFactory;
|
|
import org.gcube.common.keycloak.model.TokenResponse;
|
|
import org.gcube.common.security.Owner;
|
|
|
|
public class CredentialSecret extends Secret {
|
|
|
|
private static final String PROD_ROOT_SCOPE = "/d4science.research-infrastructures.eu";
|
|
|
|
public static final String BASE_URL = "https://url.d4science.org";
|
|
public static final String SERVICE_PATH = "/auth/realms/d4science/protocol/openid-connect/token";
|
|
|
|
public static String getServiceURL(String context) {
|
|
if(context.startsWith(PROD_ROOT_SCOPE)) {
|
|
return BASE_URL;
|
|
}
|
|
String root = context.split("/")[1];
|
|
return BASE_URL.replace("url", "url." + root.replaceAll("\\.", "-"));
|
|
}
|
|
|
|
|
|
protected boolean initialised = false;
|
|
|
|
private String username;
|
|
private String password;
|
|
private String context;
|
|
private AccessTokenSecret accessTokenSecret;
|
|
|
|
|
|
public CredentialSecret(String username, String password, String context) {
|
|
this.username = username;
|
|
this.password = password;
|
|
this.context = context;
|
|
init();
|
|
}
|
|
|
|
private void init() {
|
|
refreshAccessToken();
|
|
}
|
|
|
|
private void refreshAccessToken() {
|
|
try {
|
|
KeycloakClient client = KeycloakClientFactory.newInstance();
|
|
URL url = new URL(getServiceURL(context)+ SERVICE_PATH);
|
|
TokenResponse response = client.queryUMAToken(url, username, password, context, null);
|
|
this.accessTokenSecret = new AccessTokenSecret(response.getAccessToken());
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public Owner getOwner() {
|
|
return this.accessTokenSecret.getOwner();
|
|
}
|
|
|
|
@Override
|
|
public String getContext() {
|
|
if (this.accessTokenSecret.isExpired())
|
|
refreshAccessToken();
|
|
return this.accessTokenSecret.getContext();
|
|
}
|
|
|
|
@Override
|
|
public Map<String, String> getHTTPAuthorizationHeaders() {
|
|
if (this.accessTokenSecret.isExpired())
|
|
refreshAccessToken();
|
|
return this.accessTokenSecret.getHTTPAuthorizationHeaders();
|
|
}
|
|
|
|
@Override
|
|
public boolean isExpired() {
|
|
return false;
|
|
}
|
|
|
|
|
|
@Override
|
|
public boolean isRefreshable() {
|
|
return false;
|
|
}
|
|
|
|
}
|