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
CredentialModelfor both password and TOTP so that Keycloak can authenticate the user? - How can I properly store the OTP secret (base32) in
CREDENTIALtable 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!
- When a user attempts to log in, I first check if they exist in Keycloak’s local database using
session.users().getUserByUsername(...). - If not found, I query my own MySQL database.
- 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
- Let Keycloak handle authentication from that point forward.
Here’s a simplified version of my method: