mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(cognito): accept the refresh_token grant on the OAuth token endpoint (#4948)
POST /cognito-idp/oauth2/token, and /oauth2/token on a custom domain, now renew a session with grant_type=refresh_token through the refresh that GetTokensFromRefreshToken uses, answering as AWS does. As on AWS, the grant requires neither ALLOW_REFRESH_TOKEN_AUTH nor any OAuth setting on the client. The client is checked before the token: a Basic header names it whatever the body says. A public client's Basic credentials are refused, and its body client_secret is ignored. Errors are 400 without WWW-Authenticate: invalid_client for a missing or unknown client, a public client's Basic credentials with an empty secret, or another pool's client on a custom domain; invalid_client with invalid_client_secret for a missing or wrong secret, or a public client's Basic credentials with a secret; invalid_request with invalid_refresh_token for an empty or absent token; and invalid_grant for a token that is not valid, expired, revoked, or another client's. The answer has access_token, expires_in, token_type, and an id_token exactly when the original sign-in issued one, and no refresh_token, as rotation is not implemented. A request without grant_type is now invalid_request with no description, as on AWS. A code grant's refresh token now carries its granted scopes, base64url encoded in a field after the family id, so a refresh keeps them instead of falling back to aws.cognito.signin.user.admin, and the pre token generation trigger is told them. API sign-ins and tokens minted before this change have no such field and refresh as before. A refresh keeps the sign-in's auth_time and origin_jti. InitiateAuth REFRESH_TOKEN_AUTH and GetTokensFromRefreshToken mint the same tokens as the token endpoint. As on AWS, a refresh of a grant holding a scope the client no longer allows is refused rather than narrowed: invalid_grant on the token endpoint, and NotAuthorizedException "Client is not allowed to request these scopes" on both APIs. The refresh token is parsed from both ends, so a username holding a pipe refreshes too. GetTokensFromRefreshToken and InitiateAuth REFRESH_TOKEN_AUTH now refuse a refresh token issued to another client with NotAuthorizedException "Refresh Token has different Client".
This commit is contained in:
1 parent
991bf3ab9e
commit
2d7ebcb51c
11 files changed
+1134
-61
No files matched your search
+10
-9
@@ -657,6 +657,9 @@ final class CognitoAuthFlowHandler {
|
||||
if (!pool.getId().equals(parts[0])) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);
|
||||
}
|
||||
CognitoService.requireRefreshTokenOfClient(client, parts);
|
||||
List<String> scopes = CognitoService.refreshTokenScopes(parts);
|
||||
CognitoService.requireScopesStillAllowed(client, scopes);
|
||||
String username = parts[1];
|
||||
long iat;
|
||||
try {
|
||||
@@ -685,14 +688,10 @@ final class CognitoAuthFlowHandler {
|
||||
throw ae;
|
||||
}
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
|
||||
clientMetadata, "TokenGeneration_RefreshTokens", List.of());
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
|
||||
auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
clientMetadata, "TokenGeneration_RefreshTokens", scopes);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", auth);
|
||||
result.put("AuthenticationResult", service.accessAndIdTokens(user, pool, client, override, refreshTokenUuid,
|
||||
scopes, iat / 1000L));
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -2068,8 +2067,10 @@ final class CognitoAuthFlowHandler {
|
||||
return service.generateAuthResult(user, pool, client, override);
|
||||
}
|
||||
|
||||
CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user) {
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens", List.of());
|
||||
/** {@code scopes} are those of the grant being refreshed, or null for a sign-in through the API. */
|
||||
CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
List<String> scopes) {
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens", scopes);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+90
-15
@@ -511,7 +511,10 @@ public class CognitoOAuthController {
|
||||
String domainPoolId) {
|
||||
String grantType = trimToNull(formParams.getFirst("grant_type"));
|
||||
if (grantType == null) {
|
||||
return oauthError("invalid_request", "grant_type is required");
|
||||
return oauthError("invalid_request");
|
||||
}
|
||||
if ("refresh_token".equals(grantType)) {
|
||||
return refreshTokens(authorization, formParams, domainPoolId);
|
||||
}
|
||||
BasicCredentials basicCredentials;
|
||||
try {
|
||||
@@ -543,7 +546,8 @@ public class CognitoOAuthController {
|
||||
return redeemAuthorizationCode(clientId, clientSecret, formParams, domainPoolId);
|
||||
}
|
||||
if (!"client_credentials".equals(grantType)) {
|
||||
return oauthError("unsupported_grant_type", "Only client_credentials and authorization_code are supported");
|
||||
return oauthError("unsupported_grant_type",
|
||||
"Only client_credentials, authorization_code and refresh_token are supported");
|
||||
}
|
||||
String scope = trimToNull(formParams.getFirst("scope"));
|
||||
|
||||
@@ -586,8 +590,7 @@ public class CognitoOAuthController {
|
||||
} catch (AwsException e) {
|
||||
return oauthError("invalid_client", "Client not found");
|
||||
}
|
||||
if (client.getClientSecret() != null && !client.getClientSecret().isBlank()
|
||||
&& !secretsEqual(client.getClientSecret(), clientSecret)) {
|
||||
if (!clientSecretMatches(client, clientSecret)) {
|
||||
return oauthError("invalid_client", "Client secret is invalid");
|
||||
}
|
||||
|
||||
@@ -617,23 +620,90 @@ public class CognitoOAuthController {
|
||||
CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId());
|
||||
Map<String, Object> authentication = cognitoService.generateAuthResultForHostedAuth(user, pool, client,
|
||||
nonceClaim(consumedCode.nonce()), consumedCode.scopes());
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("access_token", (String) authentication.get("AccessToken"));
|
||||
// Minted only for a grant with openid; AWS leaves the field out otherwise.
|
||||
if (authentication.get("IdToken") instanceof String idToken) {
|
||||
body.put("id_token", idToken);
|
||||
}
|
||||
body.put("refresh_token", (String) authentication.get("RefreshToken"));
|
||||
body.put("expires_in", ((Number) authentication.get("ExpiresIn")).longValue());
|
||||
body.put("token_type", (String) authentication.get("TokenType"));
|
||||
return Response.ok(body).type(MediaType.APPLICATION_JSON)
|
||||
.header("Cache-Control", "no-store").header("Pragma", "no-cache").build();
|
||||
return tokenResponse(authentication);
|
||||
} catch (AwsException e) {
|
||||
LOG.error("Failed to redeem Cognito authorization code", e);
|
||||
return oauthError("invalid_grant", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renews a session through the refresh shared with {@code GetTokensFromRefreshToken}, answering as
|
||||
* AWS does. The client is checked before the refresh token: a Basic header names it whatever the
|
||||
* body says, and authenticates it with the header's secret. A public client has none, so a secret
|
||||
* there is wrong and an empty one names no client; its body {@code client_secret} is ignored.
|
||||
* On a custom domain it must be a client of the domain's pool. Unlike the API's refresh, AWS does
|
||||
* not require {@code ALLOW_REFRESH_TOKEN_AUTH} or any OAuth setting here. A refreshed access token
|
||||
* keeps the scopes of the original grant, so no {@code scope} is read, and, as refresh token
|
||||
* rotation is not implemented, no new refresh token is issued.
|
||||
*/
|
||||
private Response refreshTokens(String authorization, MultivaluedMap<String, String> formParams,
|
||||
String domainPoolId) {
|
||||
BasicCredentials basic;
|
||||
try {
|
||||
basic = parseBasicCredentials(authorization);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return oauthError("invalid_client");
|
||||
}
|
||||
String clientId = basic != null ? basic.clientId() : trimToNull(formParams.getFirst("client_id"));
|
||||
String clientSecret = basic != null ? basic.clientSecret() : trimToNull(formParams.getFirst("client_secret"));
|
||||
UserPoolClient client = clientId == null ? null : clientOfDomain(clientId, domainPoolId);
|
||||
if (client == null || (basic != null && !hasSecret(client) && clientSecret == null)) {
|
||||
return oauthError("invalid_client");
|
||||
}
|
||||
if (!clientSecretMatches(client, clientSecret) || (basic != null && !hasSecret(client))) {
|
||||
return oauthError("invalid_client", "invalid_client_secret");
|
||||
}
|
||||
String refreshToken = trimToNull(formParams.getFirst("refresh_token"));
|
||||
if (refreshToken == null) {
|
||||
return oauthError("invalid_request", "invalid_refresh_token");
|
||||
}
|
||||
try {
|
||||
Map<String, Object> result = cognitoService.getTokensFromRefreshToken(clientId, refreshToken);
|
||||
return tokenResponse((Map<?, ?>) result.get("AuthenticationResult"));
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("Refused a refresh_token grant for client {0}: {1} {2}", clientId, e.getErrorCode(),
|
||||
e.getMessage());
|
||||
return oauthError("invalid_grant");
|
||||
}
|
||||
}
|
||||
|
||||
/** The client, or null when it does not exist or, on a custom domain, belongs to another pool. */
|
||||
private UserPoolClient clientOfDomain(String clientId, String domainPoolId) {
|
||||
UserPoolClient client;
|
||||
try {
|
||||
client = cognitoService.findClientById(clientId);
|
||||
} catch (AwsException e) {
|
||||
return null;
|
||||
}
|
||||
return domainPoolId == null || domainPoolId.equals(client.getUserPoolId()) ? client : null;
|
||||
}
|
||||
|
||||
private static boolean hasSecret(UserPoolClient client) {
|
||||
return client.getClientSecret() != null && !client.getClientSecret().isBlank();
|
||||
}
|
||||
|
||||
/** A client with a secret must present it; a public client needs none. */
|
||||
private boolean clientSecretMatches(UserPoolClient client, String clientSecret) {
|
||||
return !hasSecret(client) || secretsEqual(client.getClientSecret(), clientSecret);
|
||||
}
|
||||
|
||||
/** The token endpoint's answer for minted tokens, with an ID or refresh token only when one was minted. */
|
||||
private Response tokenResponse(Map<?, ?> authentication) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("access_token", (String) authentication.get("AccessToken"));
|
||||
if (authentication.get("IdToken") instanceof String idToken) {
|
||||
body.put("id_token", idToken);
|
||||
}
|
||||
if (authentication.get("RefreshToken") instanceof String refreshToken) {
|
||||
body.put("refresh_token", refreshToken);
|
||||
}
|
||||
body.put("expires_in", ((Number) authentication.get("ExpiresIn")).longValue());
|
||||
body.put("token_type", (String) authentication.get("TokenType"));
|
||||
return Response.ok(body).type(MediaType.APPLICATION_JSON)
|
||||
.header("Cache-Control", "no-store").header("Pragma", "no-cache").build();
|
||||
}
|
||||
|
||||
private Response redirect(String redirectUri, Map<String, String> parameters) {
|
||||
String location = redirectUri + (redirectUri.contains("?") ? '&' : '?') + formEncode(parameters);
|
||||
return Response.status(Response.Status.FOUND).location(URI.create(location)).build();
|
||||
@@ -990,6 +1060,11 @@ public class CognitoOAuthController {
|
||||
return scopes;
|
||||
}
|
||||
|
||||
/** A 400 with no {@code error_description}, as AWS answers several token endpoint errors. */
|
||||
private Response oauthError(String error) {
|
||||
return oauthError(Response.Status.BAD_REQUEST, error, null);
|
||||
}
|
||||
|
||||
private Response oauthError(String error, String description) {
|
||||
return oauthError(Response.Status.BAD_REQUEST, error, description);
|
||||
}
|
||||
|
||||
@@ -113,6 +113,11 @@ public class CognitoService implements ResourceProvider {
|
||||
/** The scope of every access token from an API sign-in such as InitiateAuth, and what the user's own operations need. */
|
||||
private static final String USER_ADMIN_SCOPE = "aws.cognito.signin.user.admin";
|
||||
private static final List<String> API_SIGN_IN_SCOPES = List.of(USER_ADMIN_SCOPE);
|
||||
/**
|
||||
* Starts the refresh token field that holds an OAuth grant's scopes. A family id, a UUID, never
|
||||
* starts with it, so a token whose username holds a pipe is never read as one with scopes.
|
||||
*/
|
||||
private static final String REFRESH_TOKEN_SCOPE_FIELD = "scope=";
|
||||
|
||||
private static final String IDENTITIES_ATTRIBUTE = "identities";
|
||||
|
||||
@@ -4013,6 +4018,11 @@ public class CognitoService implements ResourceProvider {
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints new access and ID tokens from a refresh token, as the sign-in that issued it did: an OAuth
|
||||
* grant's access token keeps the grant's scopes, and has an ID token only with {@code openid}.
|
||||
* Shared by {@code GetTokensFromRefreshToken} and the OAuth token endpoint's refresh_token grant.
|
||||
*/
|
||||
public Map<String, Object> getTokensFromRefreshToken(String clientId, String refreshToken) {
|
||||
if (refreshToken == null) {
|
||||
throw new AwsException("InvalidParameterException", "RefreshToken is required", 400);
|
||||
@@ -4030,6 +4040,9 @@ public class CognitoService implements ResourceProvider {
|
||||
if (!client.getUserPoolId().equals(poolId)) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid refresh token", 400);
|
||||
}
|
||||
requireRefreshTokenOfClient(client, parts);
|
||||
List<String> scopes = refreshTokenScopes(parts);
|
||||
requireScopesStillAllowed(client, scopes);
|
||||
if (isRefreshTokenExpired(client, parts)) {
|
||||
throw new AwsException("NotAuthorizedException", "Refresh Token has expired", 400);
|
||||
}
|
||||
@@ -4044,19 +4057,37 @@ public class CognitoService implements ResourceProvider {
|
||||
|
||||
UserPool pool = describeUserPool(poolId);
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user);
|
||||
ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user, scopes);
|
||||
|
||||
// Use refresh token UUID as origin_jti for derived tokens
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
|
||||
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", auth);
|
||||
result.put("AuthenticationResult", accessAndIdTokens(user, pool, client, override, refreshTokenUuid,
|
||||
scopes, issuedAt / 1000L));
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a refresh token issued to another client of the pool, as AWS does for
|
||||
* {@code GetTokensFromRefreshToken} and {@code InitiateAuth} {@code REFRESH_TOKEN_AUTH} alike.
|
||||
*/
|
||||
static void requireRefreshTokenOfClient(UserPoolClient client, String[] refreshTokenParts) {
|
||||
if (!client.getClientId().equals(refreshTokenParts[2])) {
|
||||
throw new AwsException("NotAuthorizedException", "Refresh Token has different Client", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to refresh an OAuth grant holding a scope the client no longer allows. AWS refuses
|
||||
* rather than narrows the grant, on both APIs and the token endpoint. {@code scopes} null, a
|
||||
* sign-in through the API, holds none.
|
||||
*/
|
||||
static void requireScopesStillAllowed(UserPoolClient client, List<String> scopes) {
|
||||
List<String> allowed = client.getAllowedOAuthScopes() == null ? List.of() : client.getAllowedOAuthScopes();
|
||||
if (scopes != null && !allowed.containsAll(scopes)) {
|
||||
throw new AwsException("NotAuthorizedException", "Client is not allowed to request these scopes", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public void revokeToken(String clientId, String token, String clientSecret) {
|
||||
if (token == null || token.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "Token is required", 400);
|
||||
@@ -4137,7 +4168,7 @@ public class CognitoService implements ResourceProvider {
|
||||
List<String> scopes = scopesStillAllowed(client, grantedScopes);
|
||||
ClaimsOverride trigger = authFlowHandler.preTokenGenerationForHostedAuth(pool, client, user, scopes);
|
||||
return generateAuthResult(user, pool, client, mergeUnderProtocolClaims(trigger, protocolClaims),
|
||||
UUID.randomUUID().toString(), scopes, scopes.contains("openid"));
|
||||
UUID.randomUUID().toString(), scopes);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4210,18 +4241,42 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
|
||||
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
return generateAuthResult(user, pool, client, override, originJti, API_SIGN_IN_SCOPES, true);
|
||||
return generateAuthResult(user, pool, client, override, originJti, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param grantedScopes the scopes of the OAuth grant the tokens are minted for, or null for a
|
||||
* sign-in through the API. The refresh token keeps them, so that a refresh
|
||||
* mints the same kind of tokens.
|
||||
*/
|
||||
private Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client,
|
||||
ClaimsOverride override, String originJti,
|
||||
List<String> accessScopes, boolean withIdToken) {
|
||||
List<String> grantedScopes) {
|
||||
long issuedAt = System.currentTimeMillis();
|
||||
Map<String, Object> auth = accessAndIdTokens(user, pool, client, override, originJti, grantedScopes,
|
||||
issuedAt / 1000L);
|
||||
auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), issuedAt,
|
||||
originJti, grantedScopes));
|
||||
return auth;
|
||||
}
|
||||
|
||||
/**
|
||||
* An OAuth grant's access token carries the grant's scopes, and it has an ID token only when they
|
||||
* include {@code openid}, as on AWS. A sign-in through the API, {@code grantedScopes} null, has the
|
||||
* {@code aws.cognito.signin.user.admin} scope and always an ID token. {@code authTime} is when the
|
||||
* user signed in, which a refresh keeps.
|
||||
*/
|
||||
Map<String, Object> accessAndIdTokens(CognitoUser user, UserPool pool, UserPoolClient client,
|
||||
ClaimsOverride override, String originJti,
|
||||
List<String> grantedScopes, long authTime) {
|
||||
List<String> accessScopes = grantedScopes == null ? API_SIGN_IN_SCOPES : grantedScopes;
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti, accessScopes));
|
||||
if (withIdToken) {
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, originJti, accessScopes));
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti, accessScopes,
|
||||
authTime));
|
||||
if (grantedScopes == null || grantedScopes.contains("openid")) {
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, originJti, accessScopes,
|
||||
authTime));
|
||||
}
|
||||
auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), originJti));
|
||||
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
return auth;
|
||||
@@ -4232,15 +4287,17 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
|
||||
String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
return generateSignedJwt(user, pool, type, client, override, originJti, API_SIGN_IN_SCOPES);
|
||||
return generateSignedJwt(user, pool, type, client, override, originJti, API_SIGN_IN_SCOPES, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param accessScopes the access token's {@code scope} claim before any V2 trigger changes, left
|
||||
* out when empty; ignored for an ID token
|
||||
* @param authTime the {@code auth_time} claim, epoch seconds, or null for now
|
||||
*/
|
||||
private String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client,
|
||||
ClaimsOverride override, String originJti, List<String> accessScopes) {
|
||||
ClaimsOverride override, String originJti, List<String> accessScopes,
|
||||
Long authTime) {
|
||||
String header = encodeJwtHeader(pool);
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
long lifetimeSeconds = resolveTokenLifetimeSeconds(client, type);
|
||||
@@ -4250,7 +4307,7 @@ public class CognitoService implements ResourceProvider {
|
||||
claims.put("sub", sub);
|
||||
claims.put("event_id", UUID.randomUUID().toString());
|
||||
claims.put("token_use", type);
|
||||
claims.put("auth_time", now);
|
||||
claims.put("auth_time", authTime != null ? authTime : now);
|
||||
claims.put("iss", getIssuer(pool.getId()));
|
||||
claims.put("exp", now + lifetimeSeconds);
|
||||
claims.put("iat", now);
|
||||
@@ -4937,10 +4994,6 @@ public class CognitoService implements ResourceProvider {
|
||||
: Boolean.parseBoolean(String.valueOf(value));
|
||||
}
|
||||
|
||||
int getAccessTokenExpiresInSeconds(UserPoolClient client) {
|
||||
return resolveAccessTokenLifetimeSeconds(client);
|
||||
}
|
||||
|
||||
private int resolveAccessTokenLifetimeSeconds(UserPoolClient client) {
|
||||
return resolveTokenLifetimeSeconds(client, "access");
|
||||
}
|
||||
@@ -5014,13 +5067,21 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
String buildRefreshToken(UserPool pool, String username, String clientId, String originJti) {
|
||||
/**
|
||||
* A signed {@code poolId|username|clientId|issuedAt|familyId} token. An OAuth grant's token adds a
|
||||
* field holding its scopes, base64url-encoded because a scope may contain the pipe that separates
|
||||
* the fields; a sign-in through the API, {@code grantedScopes} null, has none.
|
||||
*/
|
||||
String buildRefreshToken(UserPool pool, String username, String clientId, long issuedAt, String originJti,
|
||||
List<String> grantedScopes) {
|
||||
if (ensureRefreshTokenSecret(pool)) {
|
||||
poolStore.put(pool.getId(), pool);
|
||||
}
|
||||
long issuedAt = System.currentTimeMillis();
|
||||
String familyId = originJti != null ? originJti : UUID.randomUUID().toString();
|
||||
String raw = pool.getId() + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId;
|
||||
if (grantedScopes != null) {
|
||||
raw += "|" + REFRESH_TOKEN_SCOPE_FIELD + Base64Url.encode(String.join(" ", grantedScopes));
|
||||
}
|
||||
String signature = hmacSha256(refreshTokenSecretBytes(pool), raw);
|
||||
return Base64.getEncoder().withoutPadding()
|
||||
.encodeToString((raw + "|" + signature).getBytes(StandardCharsets.UTF_8));
|
||||
@@ -5035,29 +5096,54 @@ public class CognitoService implements ResourceProvider {
|
||||
|| Boolean.TRUE.equals(client.getEnableTokenRevocation());
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields of a refresh token whose signature verifies: {@code [poolId, username, clientId,
|
||||
* issuedAt, familyId]}, and for an OAuth grant's token a sixth, its scopes separated by spaces.
|
||||
* Only the username can hold a pipe, so the fields after it are read from the end of the token.
|
||||
*/
|
||||
String[] parseRefreshToken(String refreshToken) {
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(refreshToken);
|
||||
String raw = new String(decoded, StandardCharsets.UTF_8);
|
||||
String[] parts = raw.split("\\|", 6);
|
||||
if (parts.length != 6) {
|
||||
int signatureAt = raw.lastIndexOf('|');
|
||||
String payload = raw.substring(0, signatureAt);
|
||||
String[] parts = payload.split("\\|", -1);
|
||||
boolean hasScopes = parts[parts.length - 1].startsWith(REFRESH_TOKEN_SCOPE_FIELD);
|
||||
int trailing = hasScopes ? 4 : 3;
|
||||
if (parts.length < 2 + trailing) {
|
||||
return null;
|
||||
}
|
||||
UserPool pool = poolStore.get(parts[0]).orElse(null);
|
||||
if (pool == null || pool.getSigningSecret() == null || pool.getSigningSecret().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String payload = String.join("|", Arrays.copyOf(parts, 5));
|
||||
byte[] expectedSignature = Base64.getDecoder().decode(hmacSha256(refreshTokenSecretBytes(pool), payload));
|
||||
byte[] actualSignature = Base64.getDecoder().decode(parts[5]);
|
||||
byte[] actualSignature = Base64.getDecoder().decode(raw.substring(signatureAt + 1));
|
||||
if (!MessageDigest.isEqual(expectedSignature, actualSignature)) {
|
||||
return null;
|
||||
}
|
||||
return Arrays.copyOf(parts, 5); // [poolId, username, clientId, issuedAt, nonce]
|
||||
int usernameEnd = parts.length - trailing;
|
||||
String[] fields = new String[hasScopes ? 6 : 5];
|
||||
fields[0] = parts[0];
|
||||
fields[1] = String.join("|", Arrays.copyOfRange(parts, 1, usernameEnd));
|
||||
System.arraycopy(parts, usernameEnd, fields, 2, 3);
|
||||
if (hasScopes) {
|
||||
fields[5] = new String(Base64.getUrlDecoder().decode(
|
||||
parts[parts.length - 1].substring(REFRESH_TOKEN_SCOPE_FIELD.length())), StandardCharsets.UTF_8);
|
||||
}
|
||||
return fields;
|
||||
} catch (Exception ignored) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The scopes of the OAuth grant a parsed refresh token belongs to, or null for a sign-in through the API. */
|
||||
static List<String> refreshTokenScopes(String[] parts) {
|
||||
if (parts.length < 6) {
|
||||
return null;
|
||||
}
|
||||
return parts[5].isEmpty() ? List.of() : List.of(parts[5].split(" "));
|
||||
}
|
||||
|
||||
record VerifiedAccessToken(String username, String poolId, String subject, String clientId) {}
|
||||
|
||||
/** Verified JWT details for services that enforce Cognito user-pool authorizers. */
|
||||
|
||||
Reference in new issue
Block a user