common-smartgears/src/main/java/org/gcube/smartgears/security/defaults/DefaultAuthorizationProvide...

83 lines
2.7 KiB
Java

package org.gcube.smartgears.security.defaults;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.gcube.common.keycloak.KeycloakClient;
import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.model.AccessToken.Access;
import org.gcube.common.keycloak.model.ModelUtils;
import org.gcube.common.keycloak.model.TokenResponse;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.security.secrets.AccessTokenSecret;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.security.SimpleCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultAuthorizationProvider implements AuthorizationProvider {
private static Logger LOG = LoggerFactory.getLogger(DefaultAuthorizationProvider.class);
private KeycloakClient client = KeycloakClientFactory.newInstance();
private SimpleCredentials credentials;
private String endpoint;
public DefaultAuthorizationProvider(SimpleCredentials credentials, String endpoint) {
this.credentials = credentials;
this.endpoint = endpoint;
}
@Override
public Set<String> getContexts() {
Set<String> contexts = new HashSet<String>();
try {
TokenResponse response;
if (this.endpoint == null)
response = client.queryOIDCToken(credentials.getClientID(), credentials.getSecret());
else
response = client.queryOIDCToken(new URL(this.endpoint), credentials.getClientID(), credentials.getSecret());
Map<String, Access> resourceAccess = ModelUtils.getAccessTokenFrom(response).getResourceAccess();
for (String context : resourceAccess.keySet()) {
try {
ScopeBean scope = new ScopeBean(context.replaceAll("%2F", "/"));
contexts.add(scope.toString());
LOG.info("found context {}",context);
}catch (IllegalArgumentException e) {
LOG.warn("invalid context found in token: {}", context);
}
}
} catch (Exception e) {
LOG.error("error getting OIDToken from keycloak",e);
return Collections.emptySet();
}
return contexts;
}
@Override
public Secret getSecretForContext(String context) {
try {
TokenResponse response;
if (this.endpoint == null)
response = client.queryUMAToken(credentials.getClientID(), credentials.getSecret(), context, null);
else
response = client.queryUMAToken(new URL(this.endpoint), credentials.getClientID(), credentials.getSecret(), context, null);
return new AccessTokenSecret(response.getAccessToken());
} catch (Exception e) {
LOG.error("error getting OIDToken from keycloak",e);
throw new RuntimeException("error getting access token for context "+context, e);
}
}
}