85 lines
2.3 KiB
Java
85 lines
2.3 KiB
Java
package org.gcube.common.security.secrets;
|
|
|
|
import java.util.Map;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
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;
|
|
|
|
/**
|
|
* @author Luca Frosini (ISTI - CNR)
|
|
*/
|
|
public class AccessTokenSecret extends Secret {
|
|
|
|
//private static final Logger logger = LoggerFactory.getLogger(JWTSecret.class);
|
|
|
|
/**
|
|
* The interval of time expressed in milliseconds used as guard to refresh the token before that it expires .
|
|
* TimeUnit has been used to in place of just
|
|
* using the number to have a clearer code
|
|
*/
|
|
public static final long TOLERANCE = TimeUnit.MILLISECONDS.toMillis(200);
|
|
|
|
private String accessToken;
|
|
|
|
|
|
private String context;
|
|
private UmaTokenSecret umaTokenSecret;
|
|
|
|
protected boolean initialised = false;
|
|
|
|
public AccessTokenSecret(String accessToken, String context) {
|
|
this.accessToken = accessToken;
|
|
this.context = context;
|
|
init();
|
|
}
|
|
|
|
private synchronized void init() {
|
|
try {
|
|
KeycloakClient client = KeycloakClientFactory.newInstance();
|
|
TokenResponse tokenResponse = client.queryUMAToken(context, "Bearer "+accessToken, context, null);
|
|
this.umaTokenSecret = new UmaTokenSecret(tokenResponse.getAccessToken());
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
private synchronized void refreshAccessToken() {
|
|
try {
|
|
KeycloakClient client = KeycloakClientFactory.newInstance();
|
|
TokenResponse tokenResponse = client.queryUMAToken(context, "Bearer "+accessToken, context, null);
|
|
this.umaTokenSecret = new UmaTokenSecret(tokenResponse.getAccessToken());
|
|
} catch (Exception e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public Owner getOwner() {
|
|
return this.umaTokenSecret.getOwner();
|
|
}
|
|
|
|
@Override
|
|
public String getContext() {
|
|
if (this.umaTokenSecret.isExpired())
|
|
refreshAccessToken();
|
|
return this.umaTokenSecret.getContext();
|
|
}
|
|
|
|
@Override
|
|
public Map<String, String> getHTTPAuthorizationHeaders() {
|
|
if (this.umaTokenSecret.isExpired())
|
|
refreshAccessToken();
|
|
return this.umaTokenSecret.getHTTPAuthorizationHeaders();
|
|
}
|
|
|
|
@Override
|
|
public boolean isValid() {
|
|
if (this.umaTokenSecret.isExpired())
|
|
refreshAccessToken();
|
|
return this.umaTokenSecret.isValid();
|
|
}
|
|
|
|
} |