Creating user via Admin REST API using other oauth2 client than "admin-cli"

Is is possible the create users via Admin REST API using other client than “admin-cli” ?

My scenario:

I would like to be able to create Realms, Roles ,Users from my application.

  1. User logs into the application with “foo” client using standard flow.
  2. User wants to create user in the app. → user create api call to Keycloak relaying the authorization token.

If the admin logs in (has the admin role) he can create realms, roles, clients this way. But the user creation is forbidden. ( {“error” = “unknown error”})

In other words, if i request a token like this:

POST /auth/realms/master/protocol/openid-connect/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Host: localhost:9000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 102
grant_type=password&username=admin&password=admin&scope=profile&client_id=foo&client_secret=

then using the token I can create new realms, new roles in those realms, new clients in those realms, but i can not create new users. (foo client using “realm roles” protocol mapper)

I can only create new users using the “admin-cli” client. Is this the intended way, what is so special about this client? I cant find any special settings for this client.

Thank you.

1 Like

Hey, I am having the same error

Ok, solved.
At least for me worked by using client_credentials as grant type:

TOKEN=$(curl -s --location --request POST 'http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=my-client' \
--data-urlencode 'client_secret=<your token here>' | jq -r '.access_token')

and then you can create the user:

curl -i --location --request POST 'http://localhost:8080/auth/admin/realms/myrealm/users' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $TOKEN" \
--data-raw '{"firstName":"Sergey","lastName":"Kargopolov", "email":"test@test2.com", "enabled":"true", "username":"app-user_02"}'

SOLVED! The problem was that i tried to create the user using the token generated for the master realm’s client. So when i use this token to interract with the API on an other realm it failed. The ‘admin-cli’ worked, because it’s a global client, every realm contains it.

It’s not 100% the cause, but seems logical.

What I’m end up doing is creating the user (and other objects) within the realm creation api call.