You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
common-smartgears/src/main/java/org/gcube/smartgears/security/defaults/DefaultAuthorizationProvide...

77 lines
2.5 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.security.ContextBean;
import org.gcube.common.security.secrets.Secret;
import org.gcube.common.security.secrets.UmaTokenSecret;
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 = client.queryOIDCToken(new URL(this.endpoint), credentials.getClientID(), credentials.getSecret());
Map<String, Access> resourceAccess = ModelUtils.getAccessTokenFrom(response).getResourceAccess();
for (String context : resourceAccess.keySet()) {
try {
ContextBean scope = new ContextBean(context.replaceAll("%2F", "/"));
contexts.add(scope.toString());
LOG.debug("found context {}",context);
}catch (IllegalArgumentException e) {
LOG.debug("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 = client.queryUMAToken(new URL(this.endpoint), credentials.getClientID(), credentials.getSecret(), context, null);
return new UmaTokenSecret(response.getAccessToken());
} catch (Exception e) {
LOG.error("error getting OIDToken from keycloak",e);
throw new RuntimeException("error getting access token for context "+context, e);
}
}
public SimpleCredentials getCredentials() {
return credentials;
}
}