feat(cognito): align user pool client config APIs with AWS behavior (#1360)

* feat(cognito): align CreateUserPoolClient and DescribeUserPoolClient with AWS behavior

* feat(cognito): align user pool client config APIs with AWS behavior
This commit is contained in:
shrimptails-f authored and GitHub committed 2026-06-16 00:34:17 -05:00
1 parent 174bb81dbf
commit 571d81afe3
7 files changed
+962 -33

No files matched your search

@@ -239,9 +239,9 @@ final class CognitoAuthFlowHandler {
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
clientMetadata, "TokenGeneration_RefreshTokens");
Map<String, Object> auth = new HashMap<>();
auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", tokenClientId, override));
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", tokenClientId, override));
auth.put("ExpiresIn", 3600);
auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override));
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override));
auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));
auth.put("TokenType", "Bearer");
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult", auth);
@@ -249,9 +249,9 @@ final class CognitoAuthFlowHandler {
} catch (AwsException ignored) { }
}
Map<String, Object> auth = new HashMap<>();
auth.put("AccessToken", service.generateTokenString("access", "unknown", pool, client.getClientId()));
auth.put("IdToken", service.generateTokenString("id", "unknown", pool, client.getClientId()));
auth.put("ExpiresIn", 3600);
auth.put("AccessToken", service.generateTokenString("access", "unknown", pool, client));
auth.put("IdToken", service.generateTokenString("id", "unknown", pool, client));
auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));
auth.put("TokenType", "Bearer");
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult", auth);
@@ -934,7 +934,7 @@ final class CognitoAuthFlowHandler {
String triggerSource, Map<String, String> clientMetadata) {
firePostAuthentication(pool, client, user, clientMetadata, false);
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, triggerSource);
return service.generateAuthResult(user, pool, client.getClientId(), override);
return service.generateAuthResult(user, pool, client, override);
}
CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user) {
@@ -186,7 +186,35 @@ public class CognitoJsonHandler {
request.path("GenerateSecret").asBoolean(false),
request.path("AllowedOAuthFlowsUserPoolClient").asBoolean(false),
readStringList(request.path("AllowedOAuthFlows")),
readStringList(request.path("AllowedOAuthScopes"))
readStringList(request.path("AllowedOAuthScopes")),
request.path("AnalyticsConfiguration").isObject()
? objectMapper.convertValue(request.path("AnalyticsConfiguration"),
new TypeReference<Map<String, Object>>() {})
: null,
readStringList(request.path("CallbackURLs")),
request.path("DefaultRedirectURI").asText(null),
readStringList(request.path("ExplicitAuthFlows")),
request.has("AccessTokenValidity") ? request.path("AccessTokenValidity").asInt()
: null,
request.has("IdTokenValidity") ? request.path("IdTokenValidity").asInt() : null,
readStringList(request.path("LogoutURLs")),
request.path("PreventUserExistenceErrors").asText(null),
readStringList(request.path("ReadAttributes")),
request.has("RefreshTokenValidity") ? request.path("RefreshTokenValidity").asInt()
: null,
readStringList(request.path("SupportedIdentityProviders")),
request.path("TokenValidityUnits").isObject()
? objectMapper.convertValue(request.path("TokenValidityUnits"),
new TypeReference<Map<String, String>>() {})
: null,
readStringList(request.path("WriteAttributes")),
request.path("RefreshTokenRotation").isObject()
? objectMapper.convertValue(request.path("RefreshTokenRotation"),
new TypeReference<Map<String, Object>>() {})
: null,
request.has("EnableTokenRevocation")
? request.path("EnableTokenRevocation").asBoolean()
: null
);
ObjectNode response = objectMapper.createObjectNode();
response.set("UserPoolClient", clientToNode(client));
@@ -225,8 +253,32 @@ public class CognitoJsonHandler {
request.path("ClientId").asText(),
request.has("ClientName") ? request.path("ClientName").asText() : null,
request.has("AllowedOAuthFlowsUserPoolClient") ? request.path("AllowedOAuthFlowsUserPoolClient").asBoolean() : null,
readStringList(request.path("AllowedOAuthFlows")),
readStringList(request.path("AllowedOAuthScopes"))
request.has("AllowedOAuthFlows") ? readStringList(request.path("AllowedOAuthFlows")) : null,
request.has("AllowedOAuthScopes") ? readStringList(request.path("AllowedOAuthScopes")) : null,
request.path("AnalyticsConfiguration").isObject()
? objectMapper.convertValue(request.path("AnalyticsConfiguration"),
new TypeReference<Map<String, Object>>() {})
: null,
request.has("CallbackURLs") ? readStringList(request.path("CallbackURLs")) : null,
request.has("DefaultRedirectURI") ? request.path("DefaultRedirectURI").asText(null) : null,
request.has("ExplicitAuthFlows") ? readStringList(request.path("ExplicitAuthFlows")) : null,
request.has("AccessTokenValidity") ? request.path("AccessTokenValidity").asInt() : null,
request.has("IdTokenValidity") ? request.path("IdTokenValidity").asInt() : null,
request.has("LogoutURLs") ? readStringList(request.path("LogoutURLs")) : null,
request.has("PreventUserExistenceErrors") ? request.path("PreventUserExistenceErrors").asText(null) : null,
request.has("ReadAttributes") ? readStringList(request.path("ReadAttributes")) : null,
request.has("RefreshTokenValidity") ? request.path("RefreshTokenValidity").asInt() : null,
request.has("SupportedIdentityProviders") ? readStringList(request.path("SupportedIdentityProviders")) : null,
request.path("TokenValidityUnits").isObject()
? objectMapper.convertValue(request.path("TokenValidityUnits"),
new TypeReference<Map<String, String>>() {})
: null,
request.has("WriteAttributes") ? readStringList(request.path("WriteAttributes")) : null,
request.path("RefreshTokenRotation").isObject()
? objectMapper.convertValue(request.path("RefreshTokenRotation"),
new TypeReference<Map<String, Object>>() {})
: null,
request.has("EnableTokenRevocation") ? request.path("EnableTokenRevocation").asBoolean() : null
);
ObjectNode response = objectMapper.createObjectNode();
response.set("UserPoolClient", clientToNode(client));
@@ -577,15 +629,15 @@ public class CognitoJsonHandler {
node.set("AutoVerifiedAttributes", objectMapper.valueToTree(p.getAutoVerifiedAttributes() != null ? p.getAutoVerifiedAttributes() : new java.util.ArrayList<>()));
node.set("AliasAttributes", objectMapper.valueToTree(p.getAliasAttributes() != null ? p.getAliasAttributes() : new java.util.ArrayList<>()));
node.set("UsernameAttributes", objectMapper.valueToTree(p.getUsernameAttributes() != null ? p.getUsernameAttributes() : new java.util.ArrayList<>()));
if (p.getSmsVerificationMessage() != null) node.put("SmsVerificationMessage", p.getSmsVerificationMessage());
if (p.getEmailVerificationMessage() != null) node.put("EmailVerificationMessage", p.getEmailVerificationMessage());
if (p.getEmailVerificationSubject() != null) node.put("EmailVerificationSubject", p.getEmailVerificationSubject());
node.set("VerificationMessageTemplate", objectMapper.valueToTree(p.getVerificationMessageTemplate() != null ? p.getVerificationMessageTemplate() : new HashMap<>()));
if (p.getSmsAuthenticationMessage() != null) node.put("SmsAuthenticationMessage", p.getSmsAuthenticationMessage());
node.put("MfaConfiguration", p.getMfaConfiguration() != null ? p.getMfaConfiguration() : "OFF");
node.set("DeviceConfiguration", objectMapper.valueToTree(p.getDeviceConfiguration() != null ? p.getDeviceConfiguration() : new HashMap<>()));
node.put("EstimatedNumberOfUsers", p.getEstimatedNumberOfUsers());
@@ -623,6 +675,42 @@ public class CognitoJsonHandler {
c.getAllowedOAuthFlows().forEach(flows::add);
ArrayNode scopes = node.putArray("AllowedOAuthScopes");
c.getAllowedOAuthScopes().forEach(scopes::add);
node.set("AnalyticsConfiguration", objectMapper.valueToTree(
c.getAnalyticsConfiguration() != null ? c.getAnalyticsConfiguration() : new HashMap<>()));
ArrayNode callbackUrls = node.putArray("CallbackURLs");
c.getCallbackURLs().forEach(callbackUrls::add);
if (c.getDefaultRedirectURI() != null) {
node.put("DefaultRedirectURI", c.getDefaultRedirectURI());
}
ArrayNode explicitAuthFlows = node.putArray("ExplicitAuthFlows");
c.getExplicitAuthFlows().forEach(explicitAuthFlows::add);
if (c.getAccessTokenValidity() != null) {
node.put("AccessTokenValidity", c.getAccessTokenValidity());
}
if (c.getIdTokenValidity() != null) {
node.put("IdTokenValidity", c.getIdTokenValidity());
}
ArrayNode logoutUrls = node.putArray("LogoutURLs");
c.getLogoutURLs().forEach(logoutUrls::add);
if (c.getPreventUserExistenceErrors() != null) {
node.put("PreventUserExistenceErrors", c.getPreventUserExistenceErrors());
}
ArrayNode readAttributes = node.putArray("ReadAttributes");
c.getReadAttributes().forEach(readAttributes::add);
if (c.getRefreshTokenValidity() != null) {
node.put("RefreshTokenValidity", c.getRefreshTokenValidity());
}
ArrayNode supportedIdentityProviders = node.putArray("SupportedIdentityProviders");
c.getSupportedIdentityProviders().forEach(supportedIdentityProviders::add);
node.set("TokenValidityUnits", objectMapper.valueToTree(
c.getTokenValidityUnits() != null ? c.getTokenValidityUnits() : new HashMap<>()));
ArrayNode writeAttributes = node.putArray("WriteAttributes");
c.getWriteAttributes().forEach(writeAttributes::add);
node.set("RefreshTokenRotation", objectMapper.valueToTree(
c.getRefreshTokenRotation() != null ? c.getRefreshTokenRotation() : new HashMap<>()));
if (c.getEnableTokenRevocation() != null) {
node.put("EnableTokenRevocation", c.getEnableTokenRevocation());
}
node.put("CreationDate", c.getCreationDate());
node.put("LastModifiedDate", c.getLastModifiedDate());
return node;
@@ -286,6 +286,22 @@ public class CognitoService {
boolean allowedOAuthFlowsUserPoolClient,
List<String> allowedOAuthFlows,
List<String> allowedOAuthScopes) {
return createUserPoolClient(userPoolId, clientName, generateSecret,
allowedOAuthFlowsUserPoolClient, allowedOAuthFlows, allowedOAuthScopes, null,
List.of(), null, List.of(), null, null, List.of(), null, List.of(), null, null,
null, List.of(), null, null);
}
public UserPoolClient createUserPoolClient(String userPoolId, String clientName,
boolean generateSecret, boolean allowedOAuthFlowsUserPoolClient,
List<String> allowedOAuthFlows, List<String> allowedOAuthScopes,
Map<String, Object> analyticsConfiguration, List<String> callbackURLs,
String defaultRedirectURI, List<String> explicitAuthFlows, Integer accessTokenValidity,
Integer idTokenValidity, List<String> logoutURLs, String preventUserExistenceErrors,
List<String> readAttributes, Integer refreshTokenValidity,
List<String> supportedIdentityProviders, Map<String, String> tokenValidityUnits,
List<String> writeAttributes, Map<String, Object> refreshTokenRotation,
Boolean enableTokenRevocation) {
describeUserPool(userPoolId);
String clientId = UUID.randomUUID().toString().replace("-", "").substring(0, 26);
UserPoolClient client = new UserPoolClient();
@@ -296,6 +312,24 @@ public class CognitoService {
client.setAllowedOAuthFlowsUserPoolClient(allowedOAuthFlowsUserPoolClient);
client.setAllowedOAuthFlows(normalizeStringList(allowedOAuthFlows));
client.setAllowedOAuthScopes(normalizeStringList(allowedOAuthScopes));
client.setAnalyticsConfiguration(copyObjectMap(analyticsConfiguration));
client.setCallbackURLs(normalizeStringList(callbackURLs));
client.setDefaultRedirectURI(defaultRedirectURI);
client.setExplicitAuthFlows(normalizeStringList(explicitAuthFlows));
client.setAccessTokenValidity(accessTokenValidity);
client.setIdTokenValidity(idTokenValidity);
client.setLogoutURLs(normalizeStringList(logoutURLs));
client.setPreventUserExistenceErrors(preventUserExistenceErrors);
client.setReadAttributes(normalizeStringList(readAttributes));
client.setRefreshTokenValidity(refreshTokenValidity);
List<String> normalizedSupportedIdentityProviders = normalizeStringList(supportedIdentityProviders);
client.setSupportedIdentityProviders(normalizedSupportedIdentityProviders.isEmpty()
? List.of("COGNITO")
: normalizedSupportedIdentityProviders);
client.setTokenValidityUnits(copyStringMap(tokenValidityUnits));
client.setWriteAttributes(normalizeStringList(writeAttributes));
client.setRefreshTokenRotation(copyObjectMap(refreshTokenRotation));
client.setEnableTokenRevocation(enableTokenRevocation != null ? enableTokenRevocation : Boolean.TRUE);
if (generateSecret) {
String clientSecret = generateSecretValue();
client.setClientSecret(clientSecret);
@@ -341,6 +375,50 @@ public class CognitoService {
Boolean allowedOAuthFlowsUserPoolClient,
List<String> allowedOAuthFlows,
List<String> allowedOAuthScopes) {
return updateUserPoolClient(
userPoolId,
clientId,
clientName,
allowedOAuthFlowsUserPoolClient,
allowedOAuthFlows,
allowedOAuthScopes,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
}
public UserPoolClient updateUserPoolClient(String userPoolId, String clientId, String clientName,
Boolean allowedOAuthFlowsUserPoolClient,
List<String> allowedOAuthFlows,
List<String> allowedOAuthScopes,
Map<String, Object> analyticsConfiguration,
List<String> callbackURLs,
String defaultRedirectURI,
List<String> explicitAuthFlows,
Integer accessTokenValidity,
Integer idTokenValidity,
List<String> logoutURLs,
String preventUserExistenceErrors,
List<String> readAttributes,
Integer refreshTokenValidity,
List<String> supportedIdentityProviders,
Map<String, String> tokenValidityUnits,
List<String> writeAttributes,
Map<String, Object> refreshTokenRotation,
Boolean enableTokenRevocation) {
UserPoolClient client = describeUserPoolClient(userPoolId, clientId);
if (clientName != null) client.setClientName(clientName);
if (allowedOAuthFlowsUserPoolClient != null) {
@@ -352,6 +430,51 @@ public class CognitoService {
if (allowedOAuthScopes != null) {
client.setAllowedOAuthScopes(normalizeStringList(allowedOAuthScopes));
}
if (analyticsConfiguration != null) {
client.setAnalyticsConfiguration(copyObjectMap(analyticsConfiguration));
}
if (callbackURLs != null) {
client.setCallbackURLs(normalizeStringList(callbackURLs));
}
if (defaultRedirectURI != null) {
client.setDefaultRedirectURI(defaultRedirectURI);
}
if (explicitAuthFlows != null) {
client.setExplicitAuthFlows(normalizeStringList(explicitAuthFlows));
}
if (accessTokenValidity != null) {
client.setAccessTokenValidity(accessTokenValidity);
}
if (idTokenValidity != null) {
client.setIdTokenValidity(idTokenValidity);
}
if (logoutURLs != null) {
client.setLogoutURLs(normalizeStringList(logoutURLs));
}
if (preventUserExistenceErrors != null) {
client.setPreventUserExistenceErrors(preventUserExistenceErrors);
}
if (readAttributes != null) {
client.setReadAttributes(normalizeStringList(readAttributes));
}
if (refreshTokenValidity != null) {
client.setRefreshTokenValidity(refreshTokenValidity);
}
if (supportedIdentityProviders != null) {
client.setSupportedIdentityProviders(normalizeStringList(supportedIdentityProviders));
}
if (tokenValidityUnits != null) {
client.setTokenValidityUnits(copyStringMap(tokenValidityUnits));
}
if (writeAttributes != null) {
client.setWriteAttributes(normalizeStringList(writeAttributes));
}
if (refreshTokenRotation != null) {
client.setRefreshTokenRotation(copyObjectMap(refreshTokenRotation));
}
if (enableTokenRevocation != null) {
client.setEnableTokenRevocation(enableTokenRevocation);
}
client.setLastModifiedDate(System.currentTimeMillis() / 1000L);
clientStore.put(clientId, client);
@@ -1010,7 +1133,7 @@ public class CognitoService {
Map<String, Object> response = new LinkedHashMap<>();
response.put("access_token", generateClientAccessToken(client, pool, normalizedScope));
response.put("token_type", "Bearer");
response.put("expires_in", 3600);
response.put("expires_in", resolveAccessTokenLifetimeSeconds(client));
return response;
}
@@ -1078,32 +1201,36 @@ public class CognitoService {
if (!client.getUserPoolId().equals(poolId)) {
throw new AwsException("NotAuthorizedException", "Invalid refresh token", 400);
}
if (isRefreshTokenExpired(client, parts)) {
throw new AwsException("NotAuthorizedException", "Refresh Token has expired", 400);
}
UserPool pool = describeUserPool(poolId);
CognitoUser user = adminGetUser(poolId, username);
ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user);
Map<String, Object> auth = new HashMap<>();
auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId, override));
auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId, override));
auth.put("ExpiresIn", 3600);
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override));
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override));
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
auth.put("TokenType", "Bearer");
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult", auth);
return result;
}
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, String clientId, ClaimsOverride override) {
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override) {
Map<String, Object> auth = new HashMap<>();
auth.put("AccessToken", generateSignedJwt(user, pool, "access", clientId, override));
auth.put("IdToken", generateSignedJwt(user, pool, "id", clientId, override));
auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), clientId));
auth.put("ExpiresIn", 3600);
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override));
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override));
auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), client.getClientId()));
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
auth.put("TokenType", "Bearer");
return auth;
}
String generateSignedJwt(CognitoUser user, UserPool pool, String type, String clientId, ClaimsOverride override) {
String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override) {
String header = encodeJwtHeader(pool);
long now = System.currentTimeMillis() / 1000L;
long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type);
Map<String, Object> claims = new LinkedHashMap<>();
String sub = user.getAttributes().getOrDefault("sub", user.getUsername());
@@ -1113,11 +1240,12 @@ public class CognitoService {
claims.put("token_use", type);
claims.put("auth_time", now);
claims.put("iss", getIssuer(pool.getId()));
claims.put("exp", now + 3600);
claims.put("exp", now + lifetimeSeconds);
claims.put("iat", now);
claims.put("username", user.getUsername());
claims.put("email", email);
claims.put("cognito:username", user.getUsername());
String clientId = client != null ? client.getClientId() : null;
if (clientId != null && !clientId.isBlank()) {
if ("access".equals(type)) claims.put("client_id", clientId);
if ("id".equals(type)) claims.put("aud", clientId);
@@ -1202,20 +1330,22 @@ public class CognitoService {
}
}
String generateTokenString(String type, String username, UserPool pool, String clientId) {
String generateTokenString(String type, String username, UserPool pool, UserPoolClient client) {
long now = System.currentTimeMillis() / 1000L;
long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type);
String headerJson = String.format(
"{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}",
escapeJson(getSigningKeyId(pool)));
String header = Base64.getUrlEncoder().withoutPadding()
.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
String clientId = client != null ? client.getClientId() : null;
String audFragment = (clientId != null && !clientId.isBlank() && "id".equals(type))
? ",\"aud\":\"" + escapeJson(clientId) + "\""
: "";
String payloadJson = String.format(
"{\"sub\":\"%s\",\"token_use\":\"%s\",\"iss\":\"%s\"," +
"\"exp\":%d,\"iat\":%d,\"username\":\"%s\"%s}",
UUID.randomUUID(), type, escapeJson(getIssuer(pool.getId())), now + 3600, now, username, audFragment
UUID.randomUUID(), type, escapeJson(getIssuer(pool.getId())), now + lifetimeSeconds, now, username, audFragment
);
String payload = Base64.getUrlEncoder().withoutPadding()
.encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
@@ -1230,6 +1360,7 @@ public class CognitoService {
.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
long now = System.currentTimeMillis() / 1000L;
long lifetimeSeconds = resolveAccessTokenLifetimeSeconds(client);
StringBuilder payloadJson = new StringBuilder();
payloadJson.append("{")
.append("\"iss\":\"").append(escapeJson(getIssuer(pool.getId()))).append("\",")
@@ -1237,7 +1368,7 @@ public class CognitoService {
.append("\"sub\":\"").append(escapeJson(client.getClientId())).append("\",")
.append("\"client_id\":\"").append(escapeJson(client.getClientId())).append("\",")
.append("\"token_use\":\"access\",")
.append("\"exp\":").append(now + 3600).append(",")
.append("\"exp\":").append(now + lifetimeSeconds).append(",")
.append("\"iat\":").append(now).append(",")
.append("\"jti\":\"").append(UUID.randomUUID()).append("\"");
if (scope != null && !scope.isBlank()) {
@@ -1331,6 +1462,20 @@ public class CognitoService {
return normalized.isEmpty() ? null : String.join(" ", normalized);
}
private Map<String, Object> copyObjectMap(Map<String, Object> source) {
if (source == null || source.isEmpty()) {
return null;
}
return new LinkedHashMap<>(source);
}
private Map<String, String> copyStringMap(Map<String, String> source) {
if (source == null || source.isEmpty()) {
return null;
}
return new LinkedHashMap<>(source);
}
private List<ResourceServerScope> normalizeScopes(List<ResourceServerScope> scopes) {
if (scopes == null || scopes.isEmpty()) {
return List.of();
@@ -1488,8 +1633,83 @@ public class CognitoService {
user.setSrpVerifier(verifierHex);
}
int getAccessTokenExpiresInSeconds(UserPoolClient client) {
return resolveAccessTokenLifetimeSeconds(client);
}
private int resolveAccessTokenLifetimeSeconds(UserPoolClient client) {
return resolveTokenLifetimeSeconds(client, "access");
}
private int resolveTokenLifetimeSeconds(UserPoolClient client, String tokenType) {
String normalizedType = tokenType == null ? "" : tokenType.toLowerCase(Locale.ROOT);
int defaultValue;
String defaultUnit;
Integer configuredValue;
if ("refresh".equals(normalizedType)) {
defaultValue = 30;
defaultUnit = "days";
configuredValue = client != null ? client.getRefreshTokenValidity() : null;
} else if ("id".equals(normalizedType)) {
defaultValue = 1;
defaultUnit = "hours";
configuredValue = client != null ? client.getIdTokenValidity() : null;
} else {
defaultValue = 1;
defaultUnit = "hours";
configuredValue = client != null ? client.getAccessTokenValidity() : null;
}
int value = configuredValue == null ? defaultValue : configuredValue;
if ("refresh".equals(normalizedType) && value == 0) {
value = defaultValue;
} else if (value <= 0) {
value = defaultValue;
}
String unit = resolveTokenValidityUnit(client, normalizedType, defaultUnit);
long seconds = switch (unit) {
case "seconds" -> value;
case "minutes" -> value * 60L;
case "hours" -> value * 3600L;
case "days" -> value * 86400L;
default -> throw new AwsException("InvalidParameterException", "Unsupported token validity unit: " + unit, 400);
};
if (seconds > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int) seconds;
}
private String resolveTokenValidityUnit(UserPoolClient client, String tokenType, String defaultUnit) {
Map<String, String> units = client != null ? client.getTokenValidityUnits() : null;
if (units == null || units.isEmpty()) {
return defaultUnit;
}
String key = switch (tokenType) {
case "refresh" -> "RefreshToken";
case "id" -> "IdToken";
default -> "AccessToken";
};
String configured = units.get(key);
return configured == null || configured.isBlank() ? defaultUnit : configured.trim().toLowerCase(Locale.ROOT);
}
private boolean isRefreshTokenExpired(UserPoolClient client, String[] parts) {
if (parts.length < 5) {
return false;
}
try {
long issuedAt = Long.parseLong(parts[3]);
long expiresAt = issuedAt + resolveTokenLifetimeSeconds(client, "refresh");
return System.currentTimeMillis() / 1000L >= expiresAt;
} catch (NumberFormatException ignored) {
return false;
}
}
String buildRefreshToken(String poolId, String username, String clientId) {
String raw = poolId + "|" + username + "|" + clientId + "|" + UUID.randomUUID();
long issuedAt = System.currentTimeMillis() / 1000L;
String raw = poolId + "|" + username + "|" + clientId + "|" + issuedAt + "|" + UUID.randomUUID();
return Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
@@ -1497,9 +1717,12 @@ public class CognitoService {
try {
byte[] decoded = Base64.getDecoder().decode(refreshToken);
String raw = new String(decoded, StandardCharsets.UTF_8);
String[] parts = raw.split("\\|", 4);
String[] parts = raw.split("\\|", 5);
if (parts.length == 5) {
return parts; // [poolId, username, clientId, issuedAt, nonce]
}
if (parts.length == 4) {
return parts; // [poolId, username, clientId, nonce]
return new String[] { parts[0], parts[1], parts[2], "", parts[3] };
}
} catch (Exception ignored) { }
return null;
@@ -5,6 +5,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -18,6 +19,21 @@ public class UserPoolClient {
private boolean allowedOAuthFlowsUserPoolClient;
private List<String> allowedOAuthFlows = new ArrayList<>();
private List<String> allowedOAuthScopes = new ArrayList<>();
private Map<String, Object> analyticsConfiguration;
private List<String> callbackURLs = new ArrayList<>();
private String defaultRedirectURI;
private List<String> explicitAuthFlows = new ArrayList<>();
private Integer accessTokenValidity;
private Integer idTokenValidity;
private List<String> logoutURLs = new ArrayList<>();
private String preventUserExistenceErrors;
private List<String> readAttributes = new ArrayList<>();
private Integer refreshTokenValidity;
private List<String> supportedIdentityProviders = new ArrayList<>();
private Map<String, String> tokenValidityUnits;
private List<String> writeAttributes = new ArrayList<>();
private Map<String, Object> refreshTokenRotation;
private Boolean enableTokenRevocation;
private long creationDate;
private long lastModifiedDate;
@@ -60,6 +76,61 @@ public class UserPoolClient {
public List<String> getAllowedOAuthScopes() { return allowedOAuthScopes; }
public void setAllowedOAuthScopes(List<String> allowedOAuthScopes) { this.allowedOAuthScopes = allowedOAuthScopes; }
public Map<String, Object> getAnalyticsConfiguration() { return analyticsConfiguration; }
public void setAnalyticsConfiguration(Map<String, Object> analyticsConfiguration) {
this.analyticsConfiguration = analyticsConfiguration;
}
public List<String> getCallbackURLs() { return callbackURLs; }
public void setCallbackURLs(List<String> callbackURLs) { this.callbackURLs = callbackURLs; }
public String getDefaultRedirectURI() { return defaultRedirectURI; }
public void setDefaultRedirectURI(String defaultRedirectURI) { this.defaultRedirectURI = defaultRedirectURI; }
public List<String> getExplicitAuthFlows() { return explicitAuthFlows; }
public void setExplicitAuthFlows(List<String> explicitAuthFlows) { this.explicitAuthFlows = explicitAuthFlows; }
public Integer getAccessTokenValidity() { return accessTokenValidity; }
public void setAccessTokenValidity(Integer accessTokenValidity) { this.accessTokenValidity = accessTokenValidity; }
public Integer getIdTokenValidity() { return idTokenValidity; }
public void setIdTokenValidity(Integer idTokenValidity) { this.idTokenValidity = idTokenValidity; }
public List<String> getLogoutURLs() { return logoutURLs; }
public void setLogoutURLs(List<String> logoutURLs) { this.logoutURLs = logoutURLs; }
public String getPreventUserExistenceErrors() { return preventUserExistenceErrors; }
public void setPreventUserExistenceErrors(String preventUserExistenceErrors) {
this.preventUserExistenceErrors = preventUserExistenceErrors;
}
public List<String> getReadAttributes() { return readAttributes; }
public void setReadAttributes(List<String> readAttributes) { this.readAttributes = readAttributes; }
public Integer getRefreshTokenValidity() { return refreshTokenValidity; }
public void setRefreshTokenValidity(Integer refreshTokenValidity) { this.refreshTokenValidity = refreshTokenValidity; }
public List<String> getSupportedIdentityProviders() { return supportedIdentityProviders; }
public void setSupportedIdentityProviders(List<String> supportedIdentityProviders) {
this.supportedIdentityProviders = supportedIdentityProviders;
}
public Map<String, String> getTokenValidityUnits() { return tokenValidityUnits; }
public void setTokenValidityUnits(Map<String, String> tokenValidityUnits) { this.tokenValidityUnits = tokenValidityUnits; }
public List<String> getWriteAttributes() { return writeAttributes; }
public void setWriteAttributes(List<String> writeAttributes) { this.writeAttributes = writeAttributes; }
public Map<String, Object> getRefreshTokenRotation() { return refreshTokenRotation; }
public void setRefreshTokenRotation(Map<String, Object> refreshTokenRotation) {
this.refreshTokenRotation = refreshTokenRotation;
}
public Boolean getEnableTokenRevocation() { return enableTokenRevocation; }
public void setEnableTokenRevocation(Boolean enableTokenRevocation) {
this.enableTokenRevocation = enableTokenRevocation;
}
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }