semplificato

This commit is contained in:
Alfredo Oliviero 2024-02-16 16:40:50 +01:00
parent 3ba601922d
commit dff1bb1485
6 changed files with 0 additions and 1651 deletions

View File

@ -1,34 +0,0 @@
package org.gcube.keycloak;
public class ErrorMessages {
protected static final String NOT_USER_TOKEN_CONTEXT_USED = "User's information can only be retrieved through a user token (not qualified)";
protected static final String CANNOT_RETRIEVE_SERVICE_ENDPOINT_INFORMATION = "Unable to retrieve such service endpoint information";
private static final String NO_RUNTIME_RESOURCE_TEMPLATE_NAME_CATEGORY = "There is no Runtime Resource having name %s and Category %s in this scope";
protected static final String no_runtime_category(String runtime, String category) {
return String.format(NO_RUNTIME_RESOURCE_TEMPLATE_NAME_CATEGORY, runtime, category);
}
// public static final String MISSING_TOKEN = "Missing token.";
// public static final String MISSING_PARAMETERS = "Missing request
// parameters.";
// public static final String INVALID_TOKEN = "Invalid token.";
// public static final String TOKEN_GENERATION_APP_FAILED = "Token generation
// failed.";
// public static final String NOT_APP_TOKEN = "Invalid token: not belonging to
// an application.";
// public static final String NOT_APP_ID = "Invalid application id: it doesn't
// belong to an application.";
// public static final String NO_APP_PROFILE_FOUND = "There is no application
// profile for this app id/scope.";
// public static final String BAD_REQUEST = "Please check the parameter you
// passed, it seems a bad request";
// public static final String ERROR_IN_API_RESULT = "The error is reported into
// the 'message' field of the returned object";
// public static final String POST_OUTSIDE_VRE = "A post cannot be written into
// a context that is not a VRE";
// public static final String DEPRECATED_METHOD = "This method is deprecated,
// must use version 2";
}

View File

@ -1,146 +0,0 @@
package org.gcube.keycloak;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator;
import java.util.List;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KeycloakAPIFactory {
private static final Logger logger = LoggerFactory.getLogger(KeycloakAPIFactory.class);
private final static String RUNTIME_RESOURCE_NAME = "IAM";
private final static String CATEGORY = "Service";
// the singleton obj
private static KeycloakAPIFactory singleton = new KeycloakAPIFactory();
// properties that it contains
private String keycloakURL;
private String realm;
private String clientid;
private String password;
/**
* Private constructor
*/
private KeycloakAPIFactory() {
logger.info("Building KeycloakAPICredentials object");
lookupPropertiesFromIs();
logger.info("KeycloakAPICredentials object built");
}
/**
* Read the properties from the infrastructure
*/
private void lookupPropertiesFromIs() {
logger.info("Starting creating KeycloakAPICredentials");
// String ctx = SecretManagerProvider.instance.get().getContext();
// TODO: verificare che sia contesto corretto
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
logger.info("Discovering liferay user's credentials in context "
+ ctx.container().configuration().infrastructure());
try {
List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0) {
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME + " and Category "
+ CATEGORY + " in this scope.");
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME
+ " and Category " + CATEGORY + " in this scope.");
} else {
for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next();
if (accessPoint.name().equals("d4science")) {
keycloakURL = accessPoint.address();
realm = accessPoint.name();
clientid = accessPoint.username();
password = StringEncrypter.getEncrypter().decrypt(accessPoint.password());
logger.info("Found accesspoint URL = " + keycloakURL);
}
}
}
}
} catch (Exception e) {
logger.error("Unable to retrieve such service endpoint information!", e);
return;
// }finally{
// if(oldContext != null)
// ScopeProvider.instance.set(oldContext);
}
logger.info("Bean built " + toString());
}
/**
* Retrieve endpoints information from IS for DB
*
* @return list of endpoints for ckan database
* @throws Exception
*/
private List<ServiceEndpoint> getConfigurationFromIS() throws Exception {
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '" + RUNTIME_RESOURCE_NAME + "'");
query.addCondition("$resource/Profile/Category/text() eq '" + CATEGORY + "'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query);
return toReturn;
}
public static KeycloakAPIFactory getSingleton() {
if (singleton == null)
singleton = new KeycloakAPIFactory();
return singleton;
}
public String getServerURL() {
return keycloakURL;
}
public String getClientid() {
return clientid;
}
public String getPassword() {
return password;
}
public String getRealm() {
return realm;
}
public KeycloakApiClient createtKeycloakInstance(String context) {
String realm = this.getRealm();
Keycloak keycloak = KeycloakBuilder.builder()
.serverUrl(this.getServerURL())
.realm(realm)
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId(this.getClientid()) //
.clientSecret(this.getPassword()).build();
return new KeycloakApiClient(keycloak, realm, context);
}
}

View File

@ -1,108 +0,0 @@
package org.gcube.keycloak;
import java.util.List;
import org.gcube.common.authorization.library.policies.Users;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ClientsResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.slf4j.LoggerFactory;
public class KeycloakApiClient {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Users.class);
public Keycloak kclient;
public String realmName;
public String encodeContext;
public String context;
private String clientId;
public static String getClientIdContext(String context) {
return context.replace("/", "%2F");
}
public RealmResource getRealmKClient() {
return this.kclient.realm(this.realmName);
}
public static ClientRepresentation getClientReprByName(Keycloak keycloak, String realmName, String clientName) {
ClientsResource clients = keycloak.realm(realmName).clients();
return getClientReprByName(clients, clientName);
}
public static ClientRepresentation getClientReprByName(ClientsResource realmClient, String clientName) {
String clientIdContext = getClientIdContext(clientName);
// List<ClientRepresentation> clients_repr = realmClient.clients().findByClientId(clientIdContext);
// ClientRepresentation client = null;
// String id = "";
// // prende l'utlima della lista
// for (ClientRepresentation client_repr : clients_repr) {
// logger.info("found client =" + client_repr.getClientId());
// logger.info("found client id=" + client_repr.getId());
// id = client_repr.getId();
// return client_repr;
// }
// Object clientApi = clients_repr.get(id);
return null;
}
public KeycloakApiClient(Keycloak kclient, String realmName, String context) {
this.encodeContext = getClientIdContext(context);
this.context = context;
this.kclient = kclient;
this.realmName = realmName;
//ClientsResource clients = kclient.realm(realmName).clients().get*
//clients.get(context);
}
public static KeycloakApiClient getTestClient() {
String testServerUrl = "https://accounts.dev.d4science.org/"; // + "/auth" ???
String testRealmName = "d4science";
String testClientId = "id.d4science.org";
String testClientSecret = "09c26f24-3c65-4039-9fa0-e5cc4f4032cd";
String testContext = "/gcube/devsec/devVRE";
Keycloak keycloak = KeycloakBuilder.builder()
.serverUrl(testServerUrl)
.realm(testRealmName)
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId(testClientId) //
.clientSecret(testClientSecret).build();
RealmResource realmclient = keycloak.realm(testRealmName);
ClientsResource clients = realmclient.clients();
List<ClientRepresentation> ccc = keycloak.realm(testRealmName).clients().findByClientId( getClientIdContext(testContext));
String id = "";
for (ClientRepresentation client : ccc) {
logger.info("found client ="+client.getClientId());
logger.info("found client id="+client.getId());
id =client.getId();
}
ClientResource c = keycloak.realm(testRealmName).clients().get(id);
return new KeycloakApiClient(keycloak, testRealmName, testContext);
}
}

View File

@ -1,102 +0,0 @@
package org.gcube.keycloak;
import java.io.InputStream;
import java.net.URL;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import java.util.Properties;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.keycloak.DefaultKeycloakClient;
import org.gcube.common.keycloak.KeycloakClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KeycloakClientParams_UNUSED {
private static final Logger logger = LoggerFactory.getLogger(KeycloakClientParams_UNUSED.class);
public static final String CATALOGUE_NAME = "IDM";
protected static final String CLIENT_ID_SECRET_FILENAME = "config.properties";
protected static final String CLIENT_ID_PROPERTY_NAME = "clientId";
public String context;
public String clientId;
public String clientSecret;
public DefaultKeycloakClient gcubeKeycloakClient;
// Reads the property file and extracts the keycloack configuration params
protected static Entry<String, String> getClientIdAndClientSecret(String context) {
try {
Properties properties = new Properties();
ClassLoader classLoader = KeycloakClientParams_UNUSED.class.getClassLoader();
URL url = classLoader.getResource(CLIENT_ID_SECRET_FILENAME);
logger.trace("Going to read {} at {}", CLIENT_ID_SECRET_FILENAME, url.toString());
InputStream input = classLoader.getResourceAsStream(CLIENT_ID_SECRET_FILENAME);
properties.load(input);
String clientId = "IDM";
if (properties.containsKey(CLIENT_ID_PROPERTY_NAME)) {
clientId = properties.getProperty(CLIENT_ID_PROPERTY_NAME);
}
int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index);
String clientSecret = properties.getProperty(root);
SimpleEntry<String, String> entry = new SimpleEntry<String, String>(clientId, clientSecret);
return entry;
} catch (Exception e) {
throw new InternalServerErrorException(
"Unable to retrieve Application Token for context "
+ SecretManagerProvider.instance.get().getContext(),
e);
}
}
// TODO: VERIFICARE
public URL getRealmBaseURL() throws KeycloakClientException {
return this.gcubeKeycloakClient.getRealmBaseURL(this.context);
}
public URL getRealmBaseURL(String realm) throws KeycloakClientException {
return this.gcubeKeycloakClient.getRealmBaseURL(this.context, realm);
}
public URL getServerURL() {
try {
return this.getRealmBaseURL();
} catch (KeycloakClientException e) {
// That should be almost impossible
logger.warn("Cannot create base URL", e);
return null;
}
}
public String getClientid() {
return clientId;
}
// TODO: serve? implementare
public String getPassword() {
return null;
}
// TODO: VERIFICARE
public String getRealm() {
return this.context;
}
public KeycloakClientParams_UNUSED(String context) {
this.context = context;
Entry<String, String> params = getClientIdAndClientSecret(context);
this.clientId = params.getKey();
this.clientSecret = params.getKey();
this.gcubeKeycloakClient = new DefaultKeycloakClient();
}
}

View File

@ -1,78 +0,0 @@
package org.gcube.keycloak;
import java.util.List;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
/**
*
/2/users/get-profile // profilo utente corrente
/2/users/get-all-usernames
/2/users/get-all-fullnames-and-usernames
/2/users/get-usernames-by-role
/2/users/user-exists // https://howtodoinjava.com/devops/search-keycloak-users/
// attenzione al risultato. vedere in seguito
/2/users/get-oauth-profile
// eventualemente in seguito. da approfondire
/2/users/get-custom-attribute
/2/users/get-usernames-by-global-role
/2/people/profile
*
*/
public class KeycloakUserController {
//
// get-usernames-by-role
public List<UserRepresentation> getUsersByRole(ClientResource clientApi, String roleName) {
return getUsersByRole(clientApi, roleName, 0, null);
}
public List<UserRepresentation> getUsersByRole(ClientResource clientApi, String roleName, Integer firstResult, Integer maxResults) {
List<UserRepresentation> users = clientApi.roles().get(roleName).getUserMembers(firstResult, maxResults);
return users;
}
// users/get-all-usernames
// users/get-all-fullnames-and-usernames
// users/user-exists
public UserRepresentation getUserByUsername(RealmResource realmApi, String username) throws Exception {
List<UserRepresentation> users = realmApi.users().search(username);
if (users.size() == 0){
return null;
}
if (users.size() > 1){
throw new Exception("multiple users found for username " + username);
}
return users.get(0);
}
// questi saranno implementati dalle API
// from realm
// public boolean checkUserExistsRealm(RealmResource realmApi, String username) {
// List<UserRepresentation> users = realmApi.users().search(username);
// return users.size() > 0;
// }
// public String getEmailByUsername(RealmResource realmApi, String username) throws Exception {
// UserRepresentation user = getUserByUsername(realmApi, username);
// return user.getEmail();
// }
// public String getFullnamelByUsername(RealmResource realmApi, String username) throws Exception {
// UserRepresentation user = getUserByUsername(realmApi, username);
// return user.getFirstName() + user.getLastName();
// }
}

File diff suppressed because it is too large Load Diff