Create users from rest API

Hello

I use the REST API to create user in demo realm. I want to use client credential grant to do that.

I am using Keycloak 17

I use the admin-cli client_id of the master realm to create the token. I have added manage-users and realm-management to this client id in the “Service Account Roles” tabs.

I get the following token

{
“access_token”: “eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ6dE9WR0tqQ18teWhOTG1PRVU4R2hhS0hoOFJpY0VaNFNZTnpaWlhrTHdVIn0.eyJleHAiOjE2NDkyNTc5NDgsImlhdCI6MTY0OTI1Nzg4OCwianRpIjoiYzQ4NzVkMDktZjFhYy00OTVlLThhMzUtZjdjNzA4N2Q1MjdlIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9tYXN0ZXIiLCJzdWIiOiI5Y2JkNDE4Zi0zYzkzLTQ0Y2QtYjQ3Ni0zN2EwODFlN2FiNWUiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJhY3IiOiIxIiwicmVzb3VyY2VfYWNjZXNzIjp7ImFkbWluLWNsaSI6eyJyb2xlcyI6WyJyZWFsbS1tYW5hZ2VtZW50IiwibWFuYWdlLXVzZXJzIl19fSwic2NvcGUiOiJwcm9maWxlIGVtYWlsIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJjbGllbnRIb3N0IjoiMTcyLjE3LjAuMSIsImNsaWVudElkIjoiYWRtaW4tY2xpIiwicHJlZmVycmVkX3VzZXJuYW1lIjoic2VydmljZS1hY2NvdW50LWFkbWluLWNsaSIsImNsaWVudEFkZHJlc3MiOiIxNzIuMTcuMC4xIn0.RK_45QNSnyaCF5nmWliX1LMFEiiIhGk03jkNDFmM5WaR_W9hi7w4dWYOrMtdYA3DzX8TFkK1a9Veve45RSntl5eEVWAeZb8naXBYFLPa7pomxlKTtXPtDIOYGZnBdhoIXD-mxuXi4HpBdRb6_anBRasZIHixYvq0AFQO83qF3aaC-8C6_T7Ux-wvInf9nbmYBwnhLblIw-ntHZxNtcWc24iAdKhz2tM5eT20t96RBGZHMVd3szTaXxZYVBYThUuPBGyOAXVD9SYmWJaWynXJrtQNSvAw6_HS94phC0fOs-nxsGNPnziedTpfIIyUx3puRbiMJRU2eEM0BxhiZFW6Hg”,
“expires_in”: 60,
“refresh_expires_in”: 0,
“token_type”: “Bearer”,
“not-before-policy”: 0,
“scope”: “profile email”
}

We can sow previous role in that token

After that I call this url http://localhost:8080/admin/realms/master/users to create one user

I use the previous token as Bearer authentication and I send this payload in the request body

{
“id”: “1234”,
“firstName”: “Alf”,
“lastName”: “fromspace”,
“email”: “alf@from.space”,
“enabled”: “true”,
“username”: “alf”,
“attributes”: {
“isn”: “isn”
}
}

and I always receive a 403 Forbidden with this payload in body

{
“error”: “unknown_error”
}

regards

Stéphane GINER

Try adding the Client Roles “manage-users” (…) for autocreated client “demo-realm” instead for admin-cli.

(I think it is not even necessary to use the admin-cli client of the master realm. Instead, you could create a dedicated confidential client (with service accounts and client credentials grant enabled) in your demo realm. Add the Client Roles “manage-users” of client “realm-management” as servcice account roles. Do the same in tab “scope” so the roles will be added to the access tokens.)

regards,
Matthias

Thank you for your reply

I’ll test it as soon as possible and I comme back to you to tell you if it work

Regards

Stéphane GINER

Hi

It work fine, Thanks, I give you my Keycloak configuration if somebody have the same needs

First I created the Demo realm and I set those settings

Second, I request realm management to get access-token

Third, I create the user