Compare commits

..

6 Commits

7 changed files with 162 additions and 128 deletions

View File

@ -4,23 +4,28 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
## [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
- Switched to d4science-iam-client in place of keycloak-client [#28357]
## [v2.2.0]
- Switched to the new version of keycloak-client [#25295]
## [v2.1.0]
- Added remove() method in SecretManagerProvider
- Enhanced gcube-bom version
## [v2.0.0]
- Refactored code to be integrated in Smartgears [#22871]
- Fixed getRoles for JWTSecret [#22754]
## [v1.0.0]
- First Release

View File

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

View File

@ -1,12 +1,10 @@
package org.gcube.common.authorization.utils.secret;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@ -20,13 +18,7 @@ import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.authorization.utils.clientid.RenewalProvider;
import org.gcube.common.authorization.utils.user.KeycloakUser;
import org.gcube.common.authorization.utils.user.User;
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.iam.OIDCBearerAuth;
import org.gcube.common.scope.impl.ScopeBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -45,40 +37,36 @@ public class JWTSecret extends Secret {
*/
public static final long TOLERANCE = TimeUnit.MILLISECONDS.toMillis(200);
protected AccessToken accessToken;
protected TokenResponse tokenResponse;
protected RenewalProvider renewalProvider;
protected Set<String> roles;
protected ClientInfo clientInfo;
protected Caller caller;
protected String context;
protected OIDCBearerAuth oidcBearerAuth;
public JWTSecret(String token) {
super(10, token);
this.oidcBearerAuth = OIDCBearerAuth.fromAccessTokenString(token);
}
private String getTokenString() {
try {
boolean expired = false;
getAccessToken();
boolean expired = isExpired();
if(Time.currentTimeMillis()>=(accessToken.getExp()-TOLERANCE)) {
long now = Calendar.getInstance().getTimeInMillis();
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;
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) {
try {
JWTSecret renewed = (JWTSecret) renewalProvider.renew(getContext());
this.token = renewed.token;
this.accessToken = getAccessToken();
}catch (Exception e) {
logger.warn("Unable to renew the token with the RenewalProvider. I'll continue using the old token.", e);
}
@ -99,31 +87,9 @@ public class JWTSecret extends Secret {
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{
if(roles == null) {
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<>();
}
this.roles = oidcBearerAuth.getRoles();
}
return roles;
}
@ -152,7 +118,7 @@ public class JWTSecret extends Secret {
@Override
public String getContext() throws Exception {
if(context==null) {
String[] audience = getAccessToken().getAudience();
String[] audience = oidcBearerAuth.getAccessToken().getAudience();
for (String aud : audience) {
if (aud != null && aud.compareTo("") != 0) {
try {
@ -172,7 +138,7 @@ public class JWTSecret extends Secret {
@Override
public String getUsername() throws Exception {
return getAccessToken().getPreferredUsername();
return oidcBearerAuth.getAccessToken().getPreferredUsername();
}
@Override
@ -185,31 +151,15 @@ public class JWTSecret extends Secret {
public void setRenewalProvider(RenewalProvider renewalProvider) {
this.renewalProvider = renewalProvider;
}
public void setTokenResponse(TokenResponse tokenResponse) {
this.tokenResponse = tokenResponse;
}
protected boolean isExpired(AccessToken accessToken) {
return Time.currentTimeMillis()>accessToken.getExp();
}
@Override
public boolean isExpired() {
return isExpired(getAccessToken());
public boolean isExpired() throws Exception {
return oidcBearerAuth.isExpired();
}
@Override
public boolean isRefreshable() {
if(tokenResponse!=null) {
try {
RefreshToken refreshToken = ModelUtils.getRefreshTokenFrom(tokenResponse);
return isExpired(refreshToken);
} catch (Exception e) {
return false;
}
}
return false;
public boolean isRefreshable() throws Exception {
return oidcBearerAuth.canBeRefreshed();
}
@Override
@ -217,11 +167,11 @@ public class JWTSecret extends Secret {
if(user==null) {
try {
ObjectMapper objectMapper = new ObjectMapper();
String accessTokenString = objectMapper.writeValueAsString(getAccessToken());
String accessTokenString = objectMapper.writeValueAsString(oidcBearerAuth.getAccessToken());
user = objectMapper.readValue(accessTokenString, KeycloakUser.class);
user.setRoles(getRoles());
} catch (Exception e) {
throw new RuntimeException();
throw new RuntimeException(e);
}
}
return user;

View File

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

View File

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

View File

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

View File

@ -1,11 +1,22 @@
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 org.gcube.common.authorization.library.utils.Caller;
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.Secret;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -41,4 +52,86 @@ public class SecretManagerTest extends ContextTest {
String nameSurname = user.getFullName(true);
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);
}
}