Compare commits

..

No commits in common. "9ad287dca0239134104c2d3fd210c5e2935ddcf1" and "99059f1e38ac6d9d2cb05f4df08208ad1c0d8ba2" have entirely different histories.

7 changed files with 129 additions and 163 deletions

View File

@ -4,28 +4,23 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
## [v2.3.0-SNAPSHOT] ## [v2.3.0-SNAPSHOT]
- Added support for 'client_id' and backward compatibility with 'clientId' claim [#25802] - Added support for 'client_id' and backward compatibility with 'clientId' claim #25802
- Deprecated class which will be no longer available in Smartgears 4 based components - Deprecated class which will be no longer available in Smartgears 4 based components
- Switched to d4science-iam-client in place of keycloak-client [#28357]
## [v2.2.0] ## [v2.2.0]
- Switched to the new version of keycloak-client [#25295] - Switched to the new version of keycloak-client [#25295]
## [v2.1.0] ## [v2.1.0]
- Added remove() method in SecretManagerProvider - Added remove() method in SecretManagerProvider
- Enhanced gcube-bom version - Enhanced gcube-bom version
## [v2.0.0] ## [v2.0.0]
- Refactored code to be integrated in Smartgears [#22871] - Refactored code to be integrated in Smartgears [#22871]
- Fixed getRoles for JWTSecret [#22754] - Fixed getRoles for JWTSecret [#22754]
## [v1.0.0] ## [v1.0.0]
- First Release - First Release

View File

@ -2,42 +2,35 @@ package org.gcube.common.authorization.utils.clientid;
import org.gcube.common.authorization.utils.secret.JWTSecret; import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret; import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.iam.D4ScienceIAMClient; import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.iam.D4ScienceIAMClientAuthn; import org.gcube.common.keycloak.model.TokenResponse;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
public class ClientIDManager implements RenewalProvider { public class ClientIDManager implements RenewalProvider {
protected final String clientId; protected final String clientID;
protected final String clientSecret; protected final String clientSecret;
protected D4ScienceIAMClientAuthn d4ScienceIAMClientAuthn;
public ClientIDManager(String clientId, String clientSecret) { public ClientIDManager(String clientID, String clientSecret) {
this.clientId = clientId; this.clientID = clientID;
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
} }
private JWTSecret getJWTSecret(D4ScienceIAMClientAuthn d4ScienceIAMClientAuthn) {
String accessToken = d4ScienceIAMClientAuthn.getAccessTokenString();
JWTSecret jwtSecret = new JWTSecret(accessToken);
jwtSecret.setRenewalProvider(this);
return jwtSecret;
}
public Secret getSecret(String context) throws Exception { public Secret getSecret(String context) throws Exception {
D4ScienceIAMClient iamClient = D4ScienceIAMClient.newInstance(context); TokenResponse tokenResponse = KeycloakClientFactory.newInstance().queryUMAToken(context, clientID, clientSecret, context, null);
d4ScienceIAMClientAuthn = iamClient.authenticate(clientId, clientSecret, context);
return getJWTSecret(d4ScienceIAMClientAuthn); JWTSecret jwtSecret = new JWTSecret(tokenResponse.getAccessToken());
jwtSecret.setRenewalProvider(this);
jwtSecret.setTokenResponse(tokenResponse);
return jwtSecret;
} }
@Override @Override
public Secret renew(String context) throws Exception { public Secret renew(String context) throws Exception {
if(d4ScienceIAMClientAuthn!=null && d4ScienceIAMClientAuthn.canBeRefreshed()) {
d4ScienceIAMClientAuthn.refresh(clientId, clientSecret);
return getJWTSecret(d4ScienceIAMClientAuthn);
}
return getSecret(context); return getSecret(context);
} }

View File

@ -1,10 +1,12 @@
package org.gcube.common.authorization.utils.secret; package org.gcube.common.authorization.utils.secret;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Base64;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -18,7 +20,13 @@ import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.authorization.utils.clientid.RenewalProvider; import org.gcube.common.authorization.utils.clientid.RenewalProvider;
import org.gcube.common.authorization.utils.user.KeycloakUser; import org.gcube.common.authorization.utils.user.KeycloakUser;
import org.gcube.common.authorization.utils.user.User; import org.gcube.common.authorization.utils.user.User;
import org.gcube.common.iam.OIDCBearerAuth; import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.model.AccessToken;
import org.gcube.common.keycloak.model.AccessToken.Access;
import org.gcube.common.keycloak.model.ModelUtils;
import org.gcube.common.keycloak.model.RefreshToken;
import org.gcube.common.keycloak.model.TokenResponse;
import org.gcube.common.keycloak.model.util.Time;
import org.gcube.common.scope.impl.ScopeBean; import org.gcube.common.scope.impl.ScopeBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,36 +45,40 @@ public class JWTSecret extends Secret {
*/ */
public static final long TOLERANCE = TimeUnit.MILLISECONDS.toMillis(200); public static final long TOLERANCE = TimeUnit.MILLISECONDS.toMillis(200);
protected AccessToken accessToken;
protected TokenResponse tokenResponse;
protected RenewalProvider renewalProvider; protected RenewalProvider renewalProvider;
protected Set<String> roles; protected Set<String> roles;
protected ClientInfo clientInfo; protected ClientInfo clientInfo;
protected Caller caller; protected Caller caller;
protected String context; protected String context;
protected OIDCBearerAuth oidcBearerAuth;
public JWTSecret(String token) { public JWTSecret(String token) {
super(10, token); super(10, token);
this.oidcBearerAuth = OIDCBearerAuth.fromAccessTokenString(token);
} }
private String getTokenString() { private String getTokenString() {
try { try {
boolean expired = isExpired(); boolean expired = false;
getAccessToken();
long now = Calendar.getInstance().getTimeInMillis(); if(Time.currentTimeMillis()>=(accessToken.getExp()-TOLERANCE)) {
long expireTime = oidcBearerAuth.getAccessToken().getExp()*1000;
long expireWithTolerance = expireTime-TOLERANCE;
// We consider expired TOLERANCE millisecond in advance to avoid to perform
// a requests while the token is expiring and for this reason is rejected
if(!expired && now>=expireWithTolerance) {
expired = true; expired = true;
if(tokenResponse!=null) {
try {
KeycloakClientFactory.newInstance().refreshToken(getUsername(), tokenResponse);
expired = false;
}catch (Exception e) {
logger.warn("Unable to refresh the token with RefreshToken. Going to try to renew it if possible.", e);
}
}
} }
if(expired && renewalProvider!=null) { if(expired && renewalProvider!=null) {
try { try {
JWTSecret renewed = (JWTSecret) renewalProvider.renew(getContext()); JWTSecret renewed = (JWTSecret) renewalProvider.renew(getContext());
this.token = renewed.token; this.token = renewed.token;
this.accessToken = getAccessToken();
}catch (Exception e) { }catch (Exception e) {
logger.warn("Unable to renew the token with the RenewalProvider. I'll continue using the old token.", e); logger.warn("Unable to renew the token with the RenewalProvider. I'll continue using the old token.", e);
} }
@ -87,9 +99,31 @@ public class JWTSecret extends Secret {
AccessTokenProvider.instance.reset(); AccessTokenProvider.instance.reset();
} }
protected AccessToken getAccessToken() {
if(accessToken==null) {
String realUmaTokenEncoded = token.split("\\.")[1];
String realUmaToken = new String(Base64.getDecoder().decode(realUmaTokenEncoded.getBytes()));
ObjectMapper mapper = new ObjectMapper();
try {
accessToken = mapper.readValue(realUmaToken, AccessToken.class);
}catch(Exception e){
logger.error("Error parsing JWT token",e);
throw new RuntimeException("Error parsing JWT token", e);
}
}
return accessToken;
}
protected Set<String> getRoles() throws Exception{ protected Set<String> getRoles() throws Exception{
if(roles == null) { if(roles == null) {
this.roles = oidcBearerAuth.getRoles(); Map<String,Access> accesses = getAccessToken().getResourceAccess();
String context = getContext();
Access access = accesses.get(URLEncoder.encode(context, StandardCharsets.UTF_8.toString()));
if(access != null) {
roles = access.getRoles();
}else {
roles = new HashSet<>();
}
} }
return roles; return roles;
} }
@ -118,7 +152,7 @@ public class JWTSecret extends Secret {
@Override @Override
public String getContext() throws Exception { public String getContext() throws Exception {
if(context==null) { if(context==null) {
String[] audience = oidcBearerAuth.getAccessToken().getAudience(); String[] audience = getAccessToken().getAudience();
for (String aud : audience) { for (String aud : audience) {
if (aud != null && aud.compareTo("") != 0) { if (aud != null && aud.compareTo("") != 0) {
try { try {
@ -138,7 +172,7 @@ public class JWTSecret extends Secret {
@Override @Override
public String getUsername() throws Exception { public String getUsername() throws Exception {
return oidcBearerAuth.getAccessToken().getPreferredUsername(); return getAccessToken().getPreferredUsername();
} }
@Override @Override
@ -152,14 +186,30 @@ public class JWTSecret extends Secret {
this.renewalProvider = renewalProvider; this.renewalProvider = renewalProvider;
} }
@Override public void setTokenResponse(TokenResponse tokenResponse) {
public boolean isExpired() throws Exception { this.tokenResponse = tokenResponse;
return oidcBearerAuth.isExpired(); }
protected boolean isExpired(AccessToken accessToken) {
return Time.currentTimeMillis()>accessToken.getExp();
} }
@Override @Override
public boolean isRefreshable() throws Exception { public boolean isExpired() {
return oidcBearerAuth.canBeRefreshed(); return isExpired(getAccessToken());
}
@Override
public boolean isRefreshable() {
if(tokenResponse!=null) {
try {
RefreshToken refreshToken = ModelUtils.getRefreshTokenFrom(tokenResponse);
return isExpired(refreshToken);
} catch (Exception e) {
return false;
}
}
return false;
} }
@Override @Override
@ -167,11 +217,11 @@ public class JWTSecret extends Secret {
if(user==null) { if(user==null) {
try { try {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
String accessTokenString = objectMapper.writeValueAsString(oidcBearerAuth.getAccessToken()); String accessTokenString = objectMapper.writeValueAsString(getAccessToken());
user = objectMapper.readValue(accessTokenString, KeycloakUser.class); user = objectMapper.readValue(accessTokenString, KeycloakUser.class);
user.setRoles(getRoles()); user.setRoles(getRoles());
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException();
} }
} }
return user; return user;

View File

@ -111,9 +111,9 @@ public abstract class Secret implements Comparable<Secret> {
ScopeProvider.instance.reset(); ScopeProvider.instance.reset();
} }
public abstract boolean isExpired() throws Exception; public abstract boolean isExpired();
public abstract boolean isRefreshable() throws Exception; public abstract boolean isRefreshable();
public abstract User getUser(); public abstract User getUser();

View File

@ -160,7 +160,6 @@ public class SocialService {
HttpURLConnection httpURLConnection = gxhttpStringRequest.get(); HttpURLConnection httpURLConnection = gxhttpStringRequest.get();
String ret = getResultAsString(httpURLConnection); String ret = getResultAsString(httpURLConnection);
logger.trace("Got response from social service is {}", ret);
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(ret, GCubeUser.class); return mapper.readValue(ret, GCubeUser.class);
} catch(Exception e) { } catch(Exception e) {

View File

@ -12,8 +12,9 @@ import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.authorization.utils.secret.JWTSecret; import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret; import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.authorization.utils.secret.SecretUtility; import org.gcube.common.authorization.utils.secret.SecretUtility;
import org.gcube.common.iam.D4ScienceIAMClient; import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.iam.D4ScienceIAMClientAuthn; import org.gcube.common.keycloak.KeycloakClientHelper;
import org.gcube.common.keycloak.model.TokenResponse;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -28,9 +29,7 @@ public class ContextTest {
protected static final String CONFIG_INI_FILENAME = "config.ini"; protected static final String CONFIG_INI_FILENAME = "config.ini";
public static final String PARENT_DEFAULT_TEST_SCOPE;
public static final String DEFAULT_TEST_SCOPE; public static final String DEFAULT_TEST_SCOPE;
public static final String ALTERNATIVE_TEST_SCOPE;
public static final String GCUBE; public static final String GCUBE;
public static final String DEVNEXT; public static final String DEVNEXT;
@ -38,6 +37,12 @@ public class ContextTest {
public static final String DEVSEC; public static final String DEVSEC;
public static final String DEVVRE; public static final String DEVVRE;
private static final String ROOT_PRE;
private static final String VO_PREPROD;
protected static final String VRE_GRSF_PRE;
private static final String ROOT_PROD;
protected static final Properties properties; protected static final Properties properties;
public static final String TYPE_PROPERTY_KEY = "type"; public static final String TYPE_PROPERTY_KEY = "type";
@ -45,8 +50,6 @@ public class ContextTest {
public static final String PASSWORD_PROPERTY_KEY = "password"; public static final String PASSWORD_PROPERTY_KEY = "password";
public static final String CLIENT_ID_PROPERTY_KEY = "clientId"; public static final String CLIENT_ID_PROPERTY_KEY = "clientId";
public static final String RESOURCE_REGISTRY_URL_PROPERTY = "RESOURCE_REGISTRY_URL";
static { static {
GCUBE = "/gcube"; GCUBE = "/gcube";
DEVNEXT = GCUBE + "/devNext"; DEVNEXT = GCUBE + "/devNext";
@ -54,9 +57,14 @@ public class ContextTest {
DEVSEC = GCUBE + "/devsec"; DEVSEC = GCUBE + "/devsec";
DEVVRE = DEVSEC + "/devVRE"; DEVVRE = DEVSEC + "/devVRE";
PARENT_DEFAULT_TEST_SCOPE = GCUBE; ROOT_PRE = "/pred4s";
DEFAULT_TEST_SCOPE = DEVSEC; VO_PREPROD = ROOT_PRE + "/preprod";
ALTERNATIVE_TEST_SCOPE = DEVVRE; VRE_GRSF_PRE = VO_PREPROD + "/GRSF_Pre";
ROOT_PROD = "/d4science.research-infrastructures.eu";
DEFAULT_TEST_SCOPE = DEVVRE;
// DEFAULT_TEST_SCOPE = VRE_GRSF_PRE;
properties = new Properties(); properties = new Properties();
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(CONFIG_INI_FILENAME); InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(CONFIG_INI_FILENAME);
@ -87,22 +95,21 @@ public class ContextTest {
set(secret); set(secret);
} }
protected static String getJWTAccessToken(String context) throws Exception {
private static TokenResponse getJWTAccessToken(String context) throws Exception {
Type type = Type.valueOf(properties.get(TYPE_PROPERTY_KEY).toString()); Type type = Type.valueOf(properties.get(TYPE_PROPERTY_KEY).toString());
String accessToken = null; TokenResponse tr = null;
int index = context.indexOf('/', 1); int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index); String root = context.substring(0, index == -1 ? context.length() : index);
D4ScienceIAMClient iamClient = D4ScienceIAMClient.newInstance(root);
D4ScienceIAMClientAuthn d4ScienceIAMClientAuthn = null;
switch (type) { switch (type) {
case CLIENT_ID: case CLIENT_ID:
String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY); String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
String clientSecret = properties.getProperty(root); String clientSecret = properties.getProperty(root);
d4ScienceIAMClientAuthn = iamClient.authenticate(clientId, clientSecret, context); tr = KeycloakClientFactory.newInstance().queryUMAToken(context, clientId, clientSecret, context, null);
break; break;
case USER: case USER:
@ -110,19 +117,34 @@ public class ContextTest {
String username = properties.getProperty(USERNAME_PROPERTY_KEY); String username = properties.getProperty(USERNAME_PROPERTY_KEY);
String password = properties.getProperty(PASSWORD_PROPERTY_KEY); String password = properties.getProperty(PASSWORD_PROPERTY_KEY);
d4ScienceIAMClientAuthn = iamClient.authenticateUser(username, password, context); switch (root) {
case "/gcube":
default:
clientId = "next.d4science.org";
break;
case "/pred4s":
clientId = "pre.d4science.org";
break;
case "/d4science.research-infrastructures.eu":
clientId = "services.d4science.org";
break;
}
clientSecret = null;
tr = KeycloakClientHelper.getTokenForUser(context, username, password);
break; break;
} }
accessToken = d4ScienceIAMClientAuthn.getAccessTokenString();
logger.trace("Generated Access Token is {}", accessToken); return tr;
return accessToken;
} }
public static Secret getSecretByContextName(String context) throws Exception { public static Secret getSecretByContextName(String context) throws Exception {
String accessToken = getJWTAccessToken(context); TokenResponse tr = getJWTAccessToken(context);
Secret secret = new JWTSecret(accessToken); Secret secret = new JWTSecret(tr.getAccessToken());
return secret; return secret;
} }

View File

@ -1,22 +1,11 @@
package org.gcube.common.authorization.utils.manager; package org.gcube.common.authorization.utils.manager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set; import java.util.Set;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.authorization.utils.ContextTest; import org.gcube.common.authorization.utils.ContextTest;
import org.gcube.common.authorization.utils.clientid.ClientIDManager;
import org.gcube.common.authorization.utils.secret.GCubeSecret;
import org.gcube.common.authorization.utils.secret.JWTSecret; import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret; import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.authorization.utils.user.User; import org.gcube.common.authorization.utils.user.User;
import org.gcube.common.iam.D4ScienceIAMClient;
import org.gcube.common.iam.D4ScienceIAMClientAuthn;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -52,86 +41,4 @@ public class SecretManagerTest extends ContextTest {
String nameSurname = user.getFullName(true); String nameSurname = user.getFullName(true);
logger.debug("{} - {} - {}", username, surnameName, nameSurname); logger.debug("{} - {} - {}", username, surnameName, nameSurname);
} }
@Test
public void testClientIDManager() throws Exception {
Properties properties = new Properties();
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(CONFIG_INI_FILENAME);
try {
// load the properties file
properties.load(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
String context = DEFAULT_TEST_SCOPE;
int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index);
String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
String clientSecret = properties.getProperty(root);
if(clientId==null || clientId.compareTo("")==0 || clientSecret==null || clientSecret.compareTo("")==0) {
return;
}
ClientIDManager clientIDManager = new ClientIDManager(clientId, clientSecret);
Secret secret = clientIDManager.getSecret(context);
Map<String, String> map = secret.getHTTPAuthorizationHeaders();
logger.debug("Generated HTTP Header {}", map);
Map<String, String> newMap = clientIDManager.renew(context).getHTTPAuthorizationHeaders();
logger.debug("Refreshed HTTP Header {}", newMap);
Assert.assertTrue(map.size()==newMap.size());
for(String key : map.keySet()) {
Assert.assertTrue(map.get(key).compareTo(newMap.get(key))!=0);
}
}
@Test
public void refreshClientIDTokenTest() throws Exception {
Properties properties = new Properties();
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(CONFIG_INI_FILENAME);
try {
// load the properties file
properties.load(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
String context = DEFAULT_TEST_SCOPE;
int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index);
String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
String clientSecret = properties.getProperty(root);
if(clientId==null || clientId.compareTo("")==0 || clientSecret==null || clientSecret.compareTo("")==0) {
return;
}
D4ScienceIAMClient iamClient = D4ScienceIAMClient.newInstance(context);
D4ScienceIAMClientAuthn d4ScienceIAMClientAuthn = iamClient.authenticate(clientId, clientSecret, context);
String accessToken = d4ScienceIAMClientAuthn.getAccessTokenString();
logger.info("Generated Access Token is {}", accessToken);
if(d4ScienceIAMClientAuthn!=null && d4ScienceIAMClientAuthn.canBeRefreshed()) {
d4ScienceIAMClientAuthn.refresh(clientId, clientSecret);
String refreshedAccessToken = d4ScienceIAMClientAuthn.getAccessTokenString();
logger.info("Refreshed Access Token is {}", refreshedAccessToken);
Assert.assertTrue(accessToken.compareTo(refreshedAccessToken)!=0);
}
}
@Ignore
@Test
public void testGcubeToken() throws Exception {
GCubeSecret gCubeSecret = new GCubeSecret("");
Caller caller = gCubeSecret.getCaller();
logger.debug("caller {}", caller);
User user = gCubeSecret.getUser();
logger.debug("user {}", user);
}
} }