How to dynamically add a user to Keycloak local database from external MySQL during login?

Hello everyone,

I’m building a custom UserStorageProvider and I would like to dynamically import users from my existing MySQL database into Keycloak’s local database upon first login.

Here’s the logic I want to implement: `@Override
public UserModel getUserByUsername(RealmModel realm, String username) {
UserModel local = session.users().getUserByUsername(realm, username);
if (local != null) return local;

// If not found, query MySQL
// If found in MySQL: create and import user
// session.users().addUser(...)
// newUser.setEmail(...) etc.
// Update password credential
// Update OTP credential

}
My questions are:

  • What is the correct way to build the CredentialModel for both password and TOTP so that Keycloak can authenticate the user?
  • How can I properly store the OTP secret (base32) in CREDENTIAL table through Java SPI code?
  • Is it best practice to import the user like this and let Keycloak handle it afterward?

Any code snippets, docs, or suggestions would be appreciated. Thanks!

  1. When a user attempts to log in, I first check if they exist in Keycloak’s local database using session.users().getUserByUsername(...).
  2. If not found, I query my own MySQL database.
  3. If the user exists there, I want to:
  • Create the user in Keycloak with addUser(...)
  • Set email, firstName, lastName
  • Set the password (plaintext or hashed)
  • Set the OTP secret (Google Authenticator) if available
  1. Let Keycloak handle authentication from that point forward.

Here’s a simplified version of my method:

1 Like