fix(cognito): offer configured providers in managed login (#7518)

* fix(cognito): offer configured providers in managed login

Preserve native authentication eligibility and request parameters for federated-only and mixed clients.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

* fix(cognito): explain unavailable sign-in providers

Show an actionable managed-login error after every provider is removed, without enabling native credentials.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

---------

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-04 13:45:05 -04:00
1 parent 3b8c524df0
commit 5762323bb5
4 files changed
+149 -30

No files matched your search

+7 -4
View File
@@ -748,14 +748,15 @@ client-credentials flow:
### Managed login
Managed login signs in the pool's own users with authorization code and, optionally, PKCE.
The client needs `COGNITO` in `SupportedIdentityProviders`, `AllowedOAuthFlows=["code"]` and
Managed login offers the client's identity providers with authorization code and, optionally, PKCE.
Native sign-in needs `COGNITO` in `SupportedIdentityProviders`; a federated-only client gets provider
links without a native sign-in form. The client needs `AllowedOAuthFlows=["code"]` and
the callback in `CallbackURLs`. No domain is needed; on a custom domain the same flow runs at
`/oauth2/authorize`, `/login` and `/logout`.
1. `GET /cognito-idp/oauth2/authorize` redirects to `/cognito-idp/login` with the request's
parameters, `login_hint` included. If the browser already has a managed login session in the
pool, it skips the form and redirects straight to the callback with a code, as AWS does; the
pool and the client allows `COGNITO`, it skips the form and redirects straight to the callback with a code; the
code's tokens carry the `auth_time` of the session's sign-in, not of this request. A
`scope` the client's `AllowedOAuthScopes` does not include is refused first, as on AWS, with a
redirect to the callback carrying `error=invalid_request`, `error_description=invalid_scope`
@@ -763,7 +764,9 @@ the callback in `CallbackURLs`. No domain is needed; on a custom domain the same
2. `GET /cognito-idp/login` renders a plain username and password form, with the username filled
in from `login_hint` when the request has one. The form carries the request in hidden fields and
a CSRF token that must match the `XSRF-TOKEN` cookie set with it. With choice-based sign-in
(below), it asks for the username alone.
(below), it asks for the username alone. Links for the client's external providers retain the
authorization request, including state, nonce and PKCE. A client without `COGNITO` gets only
these links; native credential submission and explicit `identity_provider=COGNITO` are refused.
3. `POST /cognito-idp/login` checks the password as `USER_PASSWORD_AUTH` does, including
sign-in aliases and the pre and post authentication and user migration triggers, but
without the client's `ExplicitAuthFlows`. On success it sets a `cognito` session cookie
@@ -81,10 +81,8 @@ public class CognitoOAuthController {
}
/**
* Without an {@code identity_provider}, or with {@code COGNITO}, signs in one of the pool's own
* users through managed login; any other value names an external provider to federate with.
* A client that does not list COGNITO cannot use managed login, even when it supports exactly
* one other provider: the caller names that provider instead.
* Without an {@code identity_provider}, offers the client's sign-in providers through managed
* login. An explicit provider selects native sign-in or external federation.
*/
@GET
@Path("/cognito-idp/oauth2/authorize")
@@ -104,7 +102,7 @@ public class CognitoOAuthController {
relyingPartyState, nonce, codeChallenge, codeChallengeMethod, loginHint);
String provider = trimToNull(providerName);
if (provider == null || COGNITO_PROVIDER.equals(provider)) {
return authorizeWithManagedLogin(requestContext, request, sessionId);
return authorizeWithManagedLogin(requestContext, request, sessionId, provider != null);
}
AuthorizationCheck check = checkAuthorizationRequest(requestContext, request);
@@ -127,12 +125,15 @@ public class CognitoOAuthController {
* redirects to the login endpoint with the request's parameters.
*/
private Response authorizeWithManagedLogin(ContainerRequestContext requestContext, AuthorizationRequest request,
String sessionId) {
AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);
String sessionId, boolean nativeProvider) {
AuthorizationCheck check = nativeProvider
? checkManagedLoginRequest(requestContext, request)
: checkAuthorizationRequest(requestContext, request);
if (check.error() != null) {
return check.error();
}
Optional<String> code = issueAuthorizationCode(sessionId, check.client(), request);
Optional<String> code = check.client().getSupportedIdentityProviders().contains(COGNITO_PROVIDER)
? issueAuthorizationCode(sessionId, check.client(), request) : Optional.empty();
if (code.isPresent()) {
return redirectWithCode(request, code.get());
}
@@ -156,7 +157,7 @@ public class CognitoOAuthController {
@QueryParam("login_hint") String loginHint) {
AuthorizationRequest request = new AuthorizationRequest(responseType, clientId, redirectUri, scope, state,
nonce, codeChallenge, codeChallengeMethod, loginHint);
AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);
AuthorizationCheck check = checkAuthorizationRequest(requestContext, request);
if (check.error() != null) {
return check.error();
}
@@ -946,6 +947,22 @@ public class CognitoOAuthController {
*/
private Response signInPage(ContainerRequestContext requestContext, AuthorizationRequest request,
Response.Status status, String error, List<String> fields) {
UserPoolClient client = cognitoService.findClientById(request.clientId());
if (client.getSupportedIdentityProviders().isEmpty() && error == null) {
error = "No sign-in providers are enabled for this application. Contact your administrator.";
}
String authorizePath = requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY) != null
? "/oauth2/authorize" : "/cognito-idp/oauth2/authorize";
List<String> providerLinks = new ArrayList<>();
for (String provider : client.getSupportedIdentityProviders()) {
if (COGNITO_PROVIDER.equals(provider)) {
continue;
}
Map<String, String> parameters = new LinkedHashMap<>(request.parameters());
parameters.put("identity_provider", provider);
providerLinks.add(" <p><a href=\"" + escapeHtml(authorizePath + "?" + formEncode(parameters))
+ "\">Sign in with " + escapeHtml(provider) + "</a></p>");
}
String csrfToken = stateStore.generateOpaqueKey();
List<String> formFields = new ArrayList<>();
for (Map.Entry<String, String> parameter : request.parameters().entrySet()) {
@@ -954,6 +971,13 @@ public class CognitoOAuthController {
for (String field : fields) {
formFields.add(" " + field);
}
String form = client.getSupportedIdentityProviders().contains(COGNITO_PROVIDER) ? """
<form method="post" action="%s">
<input type="hidden" name="%s" value="%s">
%s
</form>
""".formatted(escapeHtml(loginPath(requestContext)), CSRF_FIELD, escapeHtml(csrfToken),
String.join("\n", formFields)) : "";
String page = """
<!doctype html>
<html lang="en">
@@ -966,16 +990,13 @@ public class CognitoOAuthController {
<main>
<h1>Sign in</h1>
%s
<form method="post" action="%s">
<input type="hidden" name="%s" value="%s">
%s
</form>
%s
</main>
</body>
</html>
""".formatted(error == null ? "" : " <p role=\"alert\">" + escapeHtml(error) + "</p>",
escapeHtml(loginPath(requestContext)), CSRF_FIELD, escapeHtml(csrfToken),
String.join("\n", formFields));
String.join("\n", providerLinks), form);
// No form-action directive: browsers apply it to the redirect after the form is submitted,
// which goes to the client's callback on another origin.
return Response.status(status)
@@ -790,23 +790,105 @@ class CognitoManagedLoginIntegrationTest {
}
@Test
void clientWithoutCognitoAmongItsProvidersCannotUseManagedLogin() throws Exception {
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"FederatedOnlyPool\"}").path("UserPool").path("Id").asText();
void federatedOnlyClientOffersItsProviderWithoutNativeCredentials() throws Exception {
Pool pool = federatedPool(false);
Map<String, String> query = authorizeRequest(pool.clientId());
Response page = loginPage(null, "/cognito-idp/oauth2/authorize", query);
assertFalse(page.asString().contains("<form"));
assertFalse(page.asString().contains("type=\"password\""));
String link = providerLink(page);
assertEquals("/cognito-idp/oauth2/authorize", URI.create(link).getPath());
assertEquals(withField(query, "identity_provider", "ExampleOidc"), queryOf(link));
follow(null, link).then().statusCode(302).header("Location", startsWith("https://idp.example.test/authorize"));
given().redirects().follow(false).queryParams(query).formParam("username", "untrusted")
.formParam("password", PASSWORD).post("/cognito-idp/login")
.then().statusCode(400).body("error", equalTo("invalid_request"));
}
@Test
void removedProvidersShowAnActionableErrorWithoutNativeFallback() throws Exception {
Pool pool = federatedPool(true);
cognitoJson("UpdateUserPoolClient", """
{"UserPoolId":"%s","ClientId":"%s","AllowedOAuthFlowsUserPoolClient":true,
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],
"SupportedIdentityProviders":[]}
""".formatted(pool.poolId(), pool.clientId(), CALLBACK));
Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()));
assertTrue(page.asString().contains("<p role=\"alert\">No sign-in providers are enabled for this application."
+ " Contact your administrator.</p>"), page.asString());
assertFalse(page.asString().contains("<form"));
assertFalse(page.asString().contains("Sign in with"));
given().redirects().follow(false).queryParams(authorizeRequest(pool.clientId()))
.formParam("username", "untrusted").formParam("password", PASSWORD).post("/cognito-idp/login")
.then().statusCode(400).body("error", equalTo("invalid_request"));
}
@Test
void mixedClientKeepsItsNativeFormAndOffersFederation() throws Exception {
Pool pool = federatedPool(true);
Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()));
assertTrue(page.asString().contains("type=\"password\""));
assertEquals("/cognito-idp/login", formAction(page.asString()));
assertEquals("ExampleOidc", queryOf(providerLink(page)).get("identity_provider"));
assertFalse(page.asString().contains("Sign in with COGNITO"));
}
@Test
void federatedProviderLinkUsesCustomDomainRootAndEscapesRequestValues() throws Exception {
Pool pool = federatedPool(false);
String domain = "federated-login.example.test";
cognitoJson("CreateUserPoolDomain", customDomain(domain, pool.poolId(), requestCertificate(domain)));
Map<String, String> query = withField(authorizeRequest(pool.clientId()), "state", "<script> & \"quoted\"");
Response page = loginPage(domain, "/oauth2/authorize", query);
String link = providerLink(page);
assertEquals("/oauth2/authorize", URI.create(link).getPath());
assertEquals(withField(query, "identity_provider", "ExampleOidc"), queryOf(link));
assertFalse(page.asString().contains("<script>"));
assertTrue(page.asString().contains("&amp;"));
follow(domain, link).then().statusCode(302).header("Location", startsWith("https://idp.example.test/authorize"));
}
@Test
void federatedOnlyClientStillRejectsExplicitNativeProvider() throws Exception {
Pool pool = federatedPool(false);
browserGet(null, "/cognito-idp/oauth2/authorize",
withField(authorizeRequest(pool.clientId()), "identity_provider", "COGNITO"), null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
}
@Test
void nativeSessionCannotBypassFederatedOnlyClientProviders() throws Exception {
Pool federated = federatedPool(false);
Pool nativePool = withUser(federated.poolId(), codeClient(federated.poolId()), "native-user");
String cookie = signIn(null, nativePool, authorizeRequest(nativePool.clientId())).getCookie("cognito");
Response response = browserGet(null, "/cognito-idp/oauth2/authorize",
authorizeRequest(federated.clientId()), cookie);
response.then().statusCode(302);
assertEquals("/cognito-idp/login", URI.create(response.getHeader("Location")).getPath());
assertFalse(queryOf(response.getHeader("Location")).containsKey("code"));
}
private static Pool federatedPool(boolean nativeProvider) throws Exception {
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"FederatedLoginPool\"}")
.path("UserPool").path("Id").asText();
cognitoJson("CreateIdentityProvider", """
{"UserPoolId":"%s","ProviderName":"ExampleOidc","ProviderType":"OIDC",
"ProviderDetails":{"authorize_url":"https://idp.example.test/authorize","client_id":"idp-client","attributes_request_method":"GET","oidc_issuer":"https://idp.example.test"}}
""".formatted(poolId));
String providers = nativeProvider ? "\"COGNITO\",\"ExampleOidc\"" : "\"ExampleOidc\"";
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"federated-only","AllowedOAuthFlowsUserPoolClient":true,
{"UserPoolId":"%s","ClientName":"federated-login","AllowedOAuthFlowsUserPoolClient":true,
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],
"SupportedIdentityProviders":["ExampleOidc"]}
""".formatted(poolId, CALLBACK)).path("UserPoolClient").path("ClientId").asText();
Map<String, String> query = authorizeRequest(clientId);
"SupportedIdentityProviders":[%s]}
""".formatted(poolId, CALLBACK, providers)).path("UserPoolClient").path("ClientId").asText();
return new Pool(poolId, clientId, null, null);
}
browserGet(null, "/cognito-idp/oauth2/authorize", query, null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
browserGet(null, "/cognito-idp/login", query, null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
private static String providerLink(Response page) {
Matcher link = Pattern.compile("<a href=\"([^\"]*)\">Sign in with ExampleOidc</a>")
.matcher(page.asString());
assertTrue(link.find(), page.asString());
return link.group(1).replace("&amp;", "&");
}
@Test
@@ -154,15 +154,28 @@ class CognitoOAuthControllerTest {
}
@Test
void authorizeRejectsManagedLoginForAClientWithoutCognito() {
void authorizeRejectsExplicitNativeProviderForAClientWithoutCognito() {
client.setSupportedIdentityProviders(List.of("ExampleOidc"));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", null,
null, null, null, null, null, null);
"COGNITO", null, null, null, null, null);
assertOAuthError(response, "invalid_request");
}
@Test
void authorizeOffersProviderSelectionForAClientWithoutCognito() {
client.setSupportedIdentityProviders(List.of("ExampleOidc"));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid",
null, null, null, null, null, null, null);
assertEquals(302, response.getStatus());
assertEquals("/cognito-idp/login?response_type=code&client_id=" + CLIENT_ID
+ "&redirect_uri=https%3A%2F%2Fapplication.example.test%2Fcallback&scope=openid",
response.getHeaderString("Location"));
}
@ParameterizedTest
@CsvSource(nullValues = "null", value = {
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, plain",