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

**URL:** <https://forum.keycloak.org/t/how-to-dynamically-add-a-user-to-keycloak-local-database-from-external-mysql-during-login/30171>\
**Category:** Miscellanaeous\
**Created:** [June 30, 2025, 2:54pm UTC](https://forum.keycloak.org/t/how-to-dynamically-add-a-user-to-keycloak-local-database-from-external-mysql-during-login/30171 "2025-06-30T14:54:11Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![okaydada](https://avatars.discourse-cdn.com/v4/letter/o/bb73d2/32.png) [@okaydada](https://forum.keycloak.org/u/okaydada)\
**Post date:** [June 30, 2025, 2:54pm UTC](https://forum.keycloak.org/t/how-to-dynamically-add-a-user-to-keycloak-local-database-from-external-mysql-during-login/30171/1 "2025-06-30T14:54:11Z")

</div>

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:
