Skip to content

Instantly share code, notes, and snippets.

@maitrungduc1410
Last active December 27, 2022 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maitrungduc1410/b20d72be66419e9cccbd08979b29012e to your computer and use it in GitHub Desktop.
Save maitrungduc1410/b20d72be66419e9cccbd08979b29012e to your computer and use it in GitHub Desktop.
Import users from OpenEdx to Keycloak with NodeJS
import KcAdminClient from "@keycloak/keycloak-admin-client";
const kcAdminClient = new KcAdminClient({
baseUrl: "http://localhost:8080",
realmName: "myrealm",
});
const credentials = {
grantType: "password",
username: "superuser",
password: "xxxxxx",
clientId: "myclient",
clientSecret: "myclientsecret",
};
await kcAdminClient.auth(credentials);
const user = await kcAdminClient.users.create({
username: "openedxuser1",
email: 'openedxuser1@gmail.com',
emailVerified: true,
firstName: "AAAAA",
lastName: "BBBBB",
enabled: true,
credentials: [
{
type: 'password',
credentialData: "{\"hashIterations\": 150000,\"algorithm\": \"pbkdf2-sha256\"}",
secretData: "{\"salt\": \"eGl5VFUzTDVHbFlI\",\"value\": \"Y+tlU1BH10IDYMycH5+4S8J3IoeakcGKjKS51jDxcEQ=\"}",
}
]
})
console.log(user)
@maitrungduc1410
Copy link
Author

maitrungduc1410 commented Dec 27, 2022

Notes

superuser must have role manage-users in order to create users. From admin console -> select your realm -> Users -> select the superuser -> Role Mapping -> Assign Role -> Filter By Clients

Password of an account from OpenEdx is in this format pbkdf2_sha256$150000$xiyTU3L5GlYH$Y+tlU1BH10IDYMycH5+4S8J3IoeakcGKjKS51jDxcEQ=

Breakdown the hashed password:

  • hashing algorithm: pbkdf2_sha256
  • iteration: 150000
  • salt: xiyTU3L5GlYH
  • hash: Y+tlU1BH10IDYMycH5+4S8J3IoeakcGKjKS51jDxcEQ=

all parts are separated by $

When we import to Keycloak, in credentials we need to put same information, except salt, we need to encode salt to base64 and ONLY take the first 16 chars of the encoded string

In our case, salt is xiyTU3L5GlYH ----> base64: eGl5VFUzTDVHbFlICg== --> first 16 chars: eGl5VFUzTDVHbFlI

After you have successfully created the user, you should be able to login to keycloak with same credentials as in OpenEdx

This solution works in latest version of Keycloak 20.0.0

@maitrungduc1410
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment