Added important comments and logs

This commit is contained in:
Luca Frosini 2021-12-14 15:01:07 +01:00
parent 4b3867f085
commit 31b15c37ae
1 changed files with 20 additions and 9 deletions

View File

@ -7,6 +7,7 @@ import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.common.authorization.library.provider.AccessTokenProvider;
@ -32,9 +33,11 @@ public class JWTSecret extends Secret {
private static final Logger logger = LoggerFactory.getLogger(JWTSecret.class);
/**
*
* The interval of time expressed in milliseconds used as guard to refresh the token before that it expires .
* TimeUnit has been used to in place of just
* using the number to have a clearer code
*/
public static long TOLERANCE = 200;
public static final long TOLERANCE = TimeUnit.MILLISECONDS.toMillis(200);
protected AccessToken accessToken;
protected RefreshToken refreshToken;
@ -52,19 +55,27 @@ public class JWTSecret extends Secret {
if(Time.currentTimeMillis()>=(accessToken.getExp()-TOLERANCE)) {
expired = true;
if(refreshToken!=null) {
ObjectMapper mapper = new ObjectMapper();
KeycloakClientFactory.newInstance().refreshToken(getUsername(), mapper.writeValueAsString(refreshToken));
expired = false;
try {
ObjectMapper mapper = new ObjectMapper();
KeycloakClientFactory.newInstance().refreshToken(getUsername(), mapper.writeValueAsString(refreshToken));
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) {
JWTSecret renewed = (JWTSecret) renewalProvider.renew();
this.token = renewed.token;
this.accessToken = getAccessToken();
try {
JWTSecret renewed = (JWTSecret) renewalProvider.renew();
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);
}
}
}catch (Exception e) {
// TODO log
logger.error("Unexpected error in the procedure to evaluate/refresh the current token. I'll continue using the old token.", e);
}
return token;
}