fix(apigateway): answer 401 when a Cognito authorizer refuses the scopes (#6636)

This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-26 09:36:16 -04:00
1 parent ce0933be9b
commit e9c37666c7
4 files changed
+16 -10

No files matched your search

@@ -1022,10 +1022,6 @@ public class ApiGatewayExecuteController {
return new AuthorizerResult(gatewayResponse(scope, GatewayResponseType.UNAUTHORIZED, 401,
"Unauthorized"), null, null);
}
if (result.failure() == CognitoUserPoolAuthorizer.Failure.ACCESS_DENIED) {
return new AuthorizerResult(gatewayResponse(scope, GatewayResponseType.ACCESS_DENIED, 403,
"User is not authorized to access this resource"), null, null);
}
return new AuthorizerResult(null, result.principalId(), result.context());
}
if ("CUSTOM".equals(authorizationType)) {
@@ -21,8 +21,7 @@ import java.util.stream.Collectors;
public class CognitoUserPoolAuthorizer {
public enum Failure {
UNAUTHORIZED,
ACCESS_DENIED
UNAUTHORIZED
}
public record Result(Failure failure, String principalId, Map<String, Object> context) {}
@@ -62,10 +61,11 @@ public class CognitoUserPoolAuthorizer {
if (!providerArns.contains(verifiedPoolArn)) {
return new Result(Failure.UNAUTHORIZED, null, null);
}
// AWS answers 401, not 403, when the token claims none of the method's scopes, ID tokens included.
List<String> requiredScopes = method.getAuthorizationScopes();
if (requiredScopes != null && !requiredScopes.isEmpty()) {
if (!"access".equals(verified.tokenUse())) {
return new Result(Failure.ACCESS_DENIED, null, null);
return new Result(Failure.UNAUTHORIZED, null, null);
}
Set<String> granted = new HashSet<>();
Object scopeClaim = verified.claims().get("scope");
@@ -73,7 +73,7 @@ public class CognitoUserPoolAuthorizer {
granted.addAll(Arrays.asList(value.trim().split("\\s+")));
}
if (requiredScopes.stream().noneMatch(granted::contains)) {
return new Result(Failure.ACCESS_DENIED, null, null);
return new Result(Failure.UNAUTHORIZED, null, null);
}
}
String principalId = String.valueOf(verified.claims().getOrDefault("sub", "unknown"));