Update 'src/main/java/org/gcube/data/access/connector/GeoNetworkConnectorRequestHandler.java'

change boolean GENERAL value to true
This commit is contained in:
Roberto Cirillo 2024-03-28 17:24:47 +01:00
parent 054c734b71
commit 0fea0a8670
1 changed files with 240 additions and 240 deletions

View File

@ -1,240 +1,240 @@
package org.gcube.data.access.connector; package org.gcube.data.access.connector;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.gcube.common.authorization.library.AuthorizationEntry; import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.GCoreEndpoint; import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.data.access.connector.rest.GCubeRestClient; import org.gcube.data.access.connector.rest.GCubeRestClient;
import org.gcube.data.access.connector.rest.entity.AccessibleCredentialsEntity; import org.gcube.data.access.connector.rest.entity.AccessibleCredentialsEntity;
import org.gcube.data.access.connector.utils.AuthenticationUtils; import org.gcube.data.access.connector.utils.AuthenticationUtils;
import org.gcube.data.access.connector.utils.GCubeCache; import org.gcube.data.access.connector.utils.GCubeCache;
import org.gcube.resources.discovery.client.api.DiscoveryClient; import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery; import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.resources.discovery.icclient.ICFactory; import org.gcube.resources.discovery.icclient.ICFactory;
import org.gcube.smartgears.handlers.application.RequestEvent; import org.gcube.smartgears.handlers.application.RequestEvent;
import org.gcube.smartgears.handlers.application.RequestHandler; import org.gcube.smartgears.handlers.application.RequestHandler;
import org.gcube.smartgears.handlers.application.request.RequestError; import org.gcube.smartgears.handlers.application.request.RequestError;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.gcube.common.authorization.client.Constants.authorizationService; import static org.gcube.common.authorization.client.Constants.authorizationService;
@XmlRootElement(name = GeoNetworkConnectorRequestHandler.REQUEST_HANDLER_NAME) @XmlRootElement(name = GeoNetworkConnectorRequestHandler.REQUEST_HANDLER_NAME)
public class GeoNetworkConnectorRequestHandler extends RequestHandler { public class GeoNetworkConnectorRequestHandler extends RequestHandler {
protected static final String REQUEST_HANDLER_NAME = "authentication-filter"; protected static final String REQUEST_HANDLER_NAME = "authentication-filter";
private static final String GEONETWORK_CREDENTIALS = "/GeoNetwork/credentials/"; private static final String GEONETWORK_CREDENTIALS = "/GeoNetwork/credentials/";
private static final String SDI = "/SDI"; private static final String SDI = "/SDI";
private static final boolean GENERAL = false; //retrieve the general credentials from SDI (without web service) private static final boolean GENERAL = true; //retrieve the general credentials from SDI (without web service)
private Logger logger; private Logger logger;
private GCubeCache<String, String> gCubeCache; private GCubeCache<String, String> gCubeCache;
private GCubeRestClient restClient = new GCubeRestClient(); private GCubeRestClient restClient = new GCubeRestClient();
public GeoNetworkConnectorRequestHandler() { public GeoNetworkConnectorRequestHandler() {
logger = LoggerFactory.getLogger(this.getClass()); logger = LoggerFactory.getLogger(this.getClass());
gCubeCache = new GCubeCache<>(AuthenticationUtils.TIME_TO_LIVE, AuthenticationUtils.TIMER_INTERVAL, gCubeCache = new GCubeCache<>(AuthenticationUtils.TIME_TO_LIVE, AuthenticationUtils.TIMER_INTERVAL,
AuthenticationUtils.MAX_ITEMS_CACHE); AuthenticationUtils.MAX_ITEMS_CACHE);
} }
@Override @Override
public String getName() { public String getName() {
return REQUEST_HANDLER_NAME; return REQUEST_HANDLER_NAME;
} }
@Override @Override
public void handleRequest(RequestEvent e) { public void handleRequest(RequestEvent e) {
System.out.println("Handling request"); System.out.println("Handling request");
HttpServletRequest httpServletRequest = e.request(); HttpServletRequest httpServletRequest = e.request();
// get host from ApplicationContext // get host from ApplicationContext
String host = e.context().container().configuration().hostname(); String host = e.context().container().configuration().hostname();
// get token from request // get token from request
String token = getToken(httpServletRequest); String token = getToken(httpServletRequest);
System.out.println("Retrieve token from request = " + token); System.out.println("Retrieve token from request = " + token);
if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(token)) { if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(token)) {
System.out.println("Token found: " + token); System.out.println("Token found: " + token);
if (validateToken(token)) { if (validateToken(token)) {
// retrieve endpoint to get credentials in Geonetwork // retrieve endpoint to get credentials in Geonetwork
String endpoint = getEndpoint(token); String endpoint = getEndpoint(token);
System.out.println("Endpoint found: " + endpoint); System.out.println("Endpoint found: " + endpoint);
// TODO - Can be the endpoint stored in the cache object? // TODO - Can be the endpoint stored in the cache object?
if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(endpoint)) { if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(endpoint)) {
String usernameCache = gCubeCache.get(AuthenticationUtils.USERNAME); String usernameCache = gCubeCache.get(AuthenticationUtils.USERNAME);
String passwordCache = gCubeCache.get(AuthenticationUtils.PASSWORD); String passwordCache = gCubeCache.get(AuthenticationUtils.PASSWORD);
String tokenCache = gCubeCache.get(AuthenticationUtils.TOKEN_CACHE); String tokenCache = gCubeCache.get(AuthenticationUtils.TOKEN_CACHE);
// check current token with tokenCache // check current token with tokenCache
if (token.equals(tokenCache)) { if (token.equals(tokenCache)) {
System.out.println("Set credentials attribute retrieved from cache " + usernameCache + " " + passwordCache); System.out.println("Set credentials attribute retrieved from cache " + usernameCache + " " + passwordCache);
httpServletRequest.setAttribute(AuthenticationUtils.USERNAME, usernameCache); httpServletRequest.setAttribute(AuthenticationUtils.USERNAME, usernameCache);
httpServletRequest.setAttribute(AuthenticationUtils.PASSWORD, passwordCache); httpServletRequest.setAttribute(AuthenticationUtils.PASSWORD, passwordCache);
} else { } else {
//get credentials //get credentials
System.out.println("RETRIEVE CREDENTIALS IN GENERAL MODE = " + GENERAL); System.out.println("RETRIEVE CREDENTIALS IN GENERAL MODE = " + GENERAL);
AccessibleCredentialsEntity accessibleCredentials = getAccessibleCredentials(endpoint, host, token, GENERAL); AccessibleCredentialsEntity accessibleCredentials = getAccessibleCredentials(endpoint, host, token, GENERAL);
System.out.println("Credentials: " + accessibleCredentials.getUsername() + "/" + accessibleCredentials.getPassword()); System.out.println("Credentials: " + accessibleCredentials.getUsername() + "/" + accessibleCredentials.getPassword());
httpServletRequest.setAttribute(AuthenticationUtils.USERNAME, accessibleCredentials.getUsername()); httpServletRequest.setAttribute(AuthenticationUtils.USERNAME, accessibleCredentials.getUsername());
httpServletRequest.setAttribute(AuthenticationUtils.PASSWORD, accessibleCredentials.getPassword()); httpServletRequest.setAttribute(AuthenticationUtils.PASSWORD, accessibleCredentials.getPassword());
// set/update data in the cache // set/update data in the cache
System.out.println("Put token in the cache: " + token); System.out.println("Put token in the cache: " + token);
gCubeCache.put(AuthenticationUtils.TOKEN_CACHE, token); gCubeCache.put(AuthenticationUtils.TOKEN_CACHE, token);
System.out.println("Put also username and password in the cache"); System.out.println("Put also username and password in the cache");
gCubeCache.put(AuthenticationUtils.USERNAME, accessibleCredentials.getUsername()); gCubeCache.put(AuthenticationUtils.USERNAME, accessibleCredentials.getUsername());
gCubeCache.put(AuthenticationUtils.PASSWORD, accessibleCredentials.getPassword()); gCubeCache.put(AuthenticationUtils.PASSWORD, accessibleCredentials.getPassword());
} }
} }
} else { } else {
logger.error("Invalid token in the request"); logger.error("Invalid token in the request");
RequestError.request_not_authorized_error.fire("Invalid token in the request"); RequestError.request_not_authorized_error.fire("Invalid token in the request");
} }
} else { } else {
System.out.println("Token not present in the request: NO/OP"); System.out.println("Token not present in the request: NO/OP");
} }
} }
@Override @Override
public String toString() { public String toString() {
return getName(); return getName();
} }
// retrieve the Token from request // retrieve the Token from request
private String getToken(HttpServletRequest httpServletRequest) { private String getToken(HttpServletRequest httpServletRequest) {
// case 1 - get token from gcube-token query-string // case 1 - get token from gcube-token query-string
String gCubeToken = httpServletRequest.getParameter(AuthenticationUtils.GCUBE_QUERY_STRING); String gCubeToken = httpServletRequest.getParameter(AuthenticationUtils.GCUBE_QUERY_STRING);
if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(gCubeToken)) { if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(gCubeToken)) {
System.out.println("Get token from query-string"); System.out.println("Get token from query-string");
return gCubeToken; return gCubeToken;
} }
// case 2 - get token from gcube-token header // case 2 - get token from gcube-token header
gCubeToken = httpServletRequest.getHeader(AuthenticationUtils.GCUBE_QUERY_STRING); gCubeToken = httpServletRequest.getHeader(AuthenticationUtils.GCUBE_QUERY_STRING);
if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(gCubeToken)) { if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(gCubeToken)) {
System.out.println("Get token from gcube-token header"); System.out.println("Get token from gcube-token header");
return gCubeToken; return gCubeToken;
} }
// case 3 - get token from basic authorization header // case 3 - get token from basic authorization header
String authorization = httpServletRequest.getHeader(AuthenticationUtils.AUTHORIZATION); String authorization = httpServletRequest.getHeader(AuthenticationUtils.AUTHORIZATION);
if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(authorization) if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(authorization)
&& authorization.startsWith(AuthenticationUtils.BASIC)) { && authorization.startsWith(AuthenticationUtils.BASIC)) {
System.out.println("Get token from basic authorization header"); System.out.println("Get token from basic authorization header");
// header = Authorization: Basic base64credentials // header = Authorization: Basic base64credentials
String base64Credentials = authorization.replace(AuthenticationUtils.BASIC, ""); String base64Credentials = authorization.replace(AuthenticationUtils.BASIC, "");
String credentials = new String(Base64.decodeBase64(base64Credentials.trim())); String credentials = new String(Base64.decodeBase64(base64Credentials.trim()));
// credentials = username:token // credentials = username:token
final String[] values = credentials.split(":", 2); final String[] values = credentials.split(":", 2);
return values[1]; return values[1];
} }
System.out.println("gcube-token not found in query-string, in header and in basic authorization header"); System.out.println("gcube-token not found in query-string, in header and in basic authorization header");
// case 4 - get token from HTML form in the password field // case 4 - get token from HTML form in the password field
gCubeToken = httpServletRequest.getParameter(AuthenticationUtils.PASSWORD); gCubeToken = httpServletRequest.getParameter(AuthenticationUtils.PASSWORD);
if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(gCubeToken)) { if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(gCubeToken)) {
System.out.println("Get token from HTML form (in the password field)"); System.out.println("Get token from HTML form (in the password field)");
String user = httpServletRequest.getParameter(AuthenticationUtils.USERNAME); String user = httpServletRequest.getParameter(AuthenticationUtils.USERNAME);
System.out.println("Get username from HTML form: " + user); System.out.println("Get username from HTML form: " + user);
if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(user) && user.equals(getUser(gCubeToken))) //check username if (AuthenticationUtils.isNotNullNotEmptyNotWhiteSpace(user) && user.equals(getUser(gCubeToken))) //check username
return gCubeToken; return gCubeToken;
System.out.println("Username doesn't match with ClientInfo of gcube"); System.out.println("Username doesn't match with ClientInfo of gcube");
} else } else
System.out.println("gcube-token also not found in the HTML form in the password field"); System.out.println("gcube-token also not found in the HTML form in the password field");
return null; return null;
} }
private String getEndpoint(String token) { private String getEndpoint(String token) {
try { try {
AuthorizationEntry authorizationEntry = authorizationService().get(token); AuthorizationEntry authorizationEntry = authorizationService().get(token);
String scope = authorizationEntry.getContext(); String scope = authorizationEntry.getContext();
System.out.println("Set scope in to " + scope); System.out.println("Set scope in to " + scope);
ScopeProvider.instance.set(scope); ScopeProvider.instance.set(scope);
SecurityTokenProvider.instance.set(token); SecurityTokenProvider.instance.set(token);
String serviceClass = String.format("$resource/Profile/ServiceClass/text() eq '%s'", String serviceClass = String.format("$resource/Profile/ServiceClass/text() eq '%s'",
AuthenticationUtils.SDI); AuthenticationUtils.SDI);
String serviceName = String.format("$resource/Profile/ServiceName/text() eq '%s'", String serviceName = String.format("$resource/Profile/ServiceName/text() eq '%s'",
AuthenticationUtils.SDI_SERVICE); AuthenticationUtils.SDI_SERVICE);
String status = String.format("$resource/Profile/DeploymentData/Status/text() eq '%s'", String status = String.format("$resource/Profile/DeploymentData/Status/text() eq '%s'",
AuthenticationUtils.READY); AuthenticationUtils.READY);
SimpleQuery query = ICFactory.queryFor(GCoreEndpoint.class).addCondition(serviceClass) SimpleQuery query = ICFactory.queryFor(GCoreEndpoint.class).addCondition(serviceClass)
.addCondition(serviceName).addCondition(status); .addCondition(serviceName).addCondition(status);
DiscoveryClient<GCoreEndpoint> client = ICFactory.clientFor(GCoreEndpoint.class); DiscoveryClient<GCoreEndpoint> client = ICFactory.clientFor(GCoreEndpoint.class);
List<GCoreEndpoint> gCoreEndpoints = client.submit(query); List<GCoreEndpoint> gCoreEndpoints = client.submit(query);
int size = gCoreEndpoints.size(); int size = gCoreEndpoints.size();
System.out.println("gCoreEndpoints size = " + size); System.out.println("gCoreEndpoints size = " + size);
if (size > 0) {//I get only the first. Usually it must be only one if (size > 0) {//I get only the first. Usually it must be only one
GCoreEndpoint gCoreEndpoint = gCoreEndpoints.get(0); GCoreEndpoint gCoreEndpoint = gCoreEndpoints.get(0);
return gCoreEndpoint.profile().endpointMap().get("org.gcube.spatial.data.sdi.SDIService").uri().toString(); return gCoreEndpoint.profile().endpointMap().get("org.gcube.spatial.data.sdi.SDIService").uri().toString();
} }
} catch (Exception ex) { } catch (Exception ex) {
logger.error("Error in getEndpoint() method: " + ex.getMessage()); logger.error("Error in getEndpoint() method: " + ex.getMessage());
} }
return null; return null;
} }
private String getUser(String token) { private String getUser(String token) {
try { try {
AuthorizationEntry authorizationEntry = authorizationService().get(token); AuthorizationEntry authorizationEntry = authorizationService().get(token);
return authorizationEntry.getClientInfo().getId(); return authorizationEntry.getClientInfo().getId();
} catch (Exception ex) { } catch (Exception ex) {
logger.error("Error in getUser() method: " + ex.getMessage()); logger.error("Error in getUser() method: " + ex.getMessage());
} }
return null; return null;
} }
private boolean validateToken(String token) { private boolean validateToken(String token) {
// TODO How to implement the validation of the token // TODO How to implement the validation of the token
System.out.println("Validate token in progress..."); System.out.println("Validate token in progress...");
return true; return true;
} }
private AccessibleCredentialsEntity getAccessibleCredentials(String endpoint, String host, String token, boolean general){ private AccessibleCredentialsEntity getAccessibleCredentials(String endpoint, String host, String token, boolean general){
if (general){ if (general){
String url = endpoint + SDI + "?" + AuthenticationUtils.GCUBE_QUERY_STRING + "=" + token; String url = endpoint + SDI + "?" + AuthenticationUtils.GCUBE_QUERY_STRING + "=" + token;
//http://sdi-d-d4s.d4science.org/sdi-service/gcube/service/SDI?gcube-token=feda0617-cd9d-4841-b6f0-e047da5d32ed-98187548"; //http://sdi-d-d4s.d4science.org/sdi-service/gcube/service/SDI?gcube-token=feda0617-cd9d-4841-b6f0-e047da5d32ed-98187548";
System.out.println("general url : " + url ); System.out.println("general url : " + url );
return restClient.getGeneralAccessibleCredentials(url, host); return restClient.getGeneralAccessibleCredentials(url, host);
}else{ }else{
/* /*
String url = endpoint + GEONETWORK_CREDENTIALS + host + "?" + AuthenticationUtils.GCUBE_QUERY_STRING + "=" + token; String url = endpoint + GEONETWORK_CREDENTIALS + host + "?" + AuthenticationUtils.GCUBE_QUERY_STRING + "=" + token;
//http://sdi-d-d4s.d4science.org:80/sdi-service/gcube/service/GeoNetwork/credentials/geonetwork-sdi.dev.d4science.org?gcube-token=feda0617-cd9d-4841-b6f0-e047da5d32ed-98187548 //http://sdi-d-d4s.d4science.org:80/sdi-service/gcube/service/GeoNetwork/credentials/geonetwork-sdi.dev.d4science.org?gcube-token=feda0617-cd9d-4841-b6f0-e047da5d32ed-98187548
System.out.println("url : " + url ); System.out.println("url : " + url );
return restClient.getAccessibleCredentials(url); return restClient.getAccessibleCredentials(url);
*/ */
String hst = "sdi-d-d4s.d4science.org"; String hst = "sdi-d-d4s.d4science.org";
String get = "/sdi-service/gcube/service/GeoNetwork/credentials/geonetwork-sdi.dev.d4science.org?gcube-token=feda0617-cd9d-4841-b6f0-e047da5d32ed-98187548"; String get = "/sdi-service/gcube/service/GeoNetwork/credentials/geonetwork-sdi.dev.d4science.org?gcube-token=feda0617-cd9d-4841-b6f0-e047da5d32ed-98187548";
System.out.println("url : " + hst + get ); System.out.println("url : " + hst + get );
return restClient.getAccessibleCredentialsHttp(hst, get); return restClient.getAccessibleCredentialsHttp(hst, get);
} }
} }
} }