Dynamic IDP Redirection + Registration for Keycloak Login

Hello,

I will be managing lots of customers who will mainly connect in via external IDPs. Because of this, I want to be able for a customer to enter their username and then if their domain is matched, redirect them to their IDP.

I have updated this:

And made it so that determineTargetIdp is passed the email which is retrieved from:
context.getHttpRequest().getDecodedFormParameters();

The key part of my code is here:
public void authenticate(AuthenticationFlowContext context) {
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
String email = formData.getFirst(“username”);
log.info(email);

UserModel user = context.getUser();
if (user == null) {
  log.info("User doesn't exist!");
  context.attempted();
  return;
}

String targetIdp = determineTargetIdp(email, context);
if (targetIdp != null) {
  redirect(context, targetIdp);
  return;
}

The login flow I am using is this:

This so far works great… except if a user doesn’t exist but there domain name is mapped to an IDP. It says “Username not found”, however in this case I want them to be registered in keycloak for this use case.

When I log in with an IDP user who doesn’t exist, this line doesn’t execute yet:
log.info(“User doesn’t exist!”);

So I think the usernameForm is validing if the user exists before it even gets to this step in my code. How can I get around this?

I could build a custom usernameForm that doesn’t do this validation if the user’s email domain matches an IDP redirection value, however this seems very long for what must be a common user requirement

Don’t make it that complicated, use the new organization feature in Keycloak 26+
I made a video about this:

Thank you, I will investigate :slight_smile: