Orzel94
Orzel94

Reputation: 123

Using admin API to add client role to user

I'm trying to use keycloak AdminAPI (https://www.keycloak.org/docs-api/3.0/rest-api/index.html#_users_resource) to create user and assign client roles. I'm receiving correct token, and user is created but assigning roles return 404.

I'm using Postman to connect with API:

/auth/realms/{realmName}/protocol/openid-connect/token
Content-Type application/x-www-form-urlencoded <-with parameters ofc
/auth/admin/realms/{realmName}/users

Content-Type application/json
Authorization Bearer {TOKEN}
Body:
{
   "username": "name",
   "enabled": true,
   "emailVerified": false,
   "firstName": "first",
   "lastName": "last",
   "credentials": [
       {
           "type": "password",
           "value": "newPas1*",
           "temporary": false
       }
   ]
}

Above works for me, but the next one doesn't

/auth/admin/realms/{realmName}/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/role-mappings/clients/realm-management

Content-Type application/json
Authorization Bearer {TOKEN}
Body:
{
   "roles": [
       {
           "id": "0830ff39-43ea-48bb-af8f-696bc420c1ce",
           "name": "create-client",
           "description": "${role_create-client}",
           "composite": false,
           "clientRole": true,
           "containerId": "344e7c81-e7a2-4a43-b013-57d7ed198eee"
       }
   ]
}

Where 'xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx' is userID returned during creation and create-client role exists

I need a way to add client role via Http request. I saw there are some keycloack implementation for java but I'm using .NET CORE so there will be the target implementation but I need to have working request first as you may guess.

Upvotes: 9

Views: 43080

Answers (2)

J. Long
J. Long

Reputation: 449

if anybody else ends up here because they are getting a 500 from KeyCloak trying to add a user to a role using the PostMan to call the following API

{{HOST_NAME}}/auth/admin/realms/{{REALM_NAME}}/users/{{POSTMAN_USER_ID}}/role-mappings/realm

then you need

  1. the auth token as a Bearer Token
  2. the body needs JSON with "id" and "name"
  3. the headers must have Content-Type and Content-Length

I was leaving off Content-Length in PostMan and that is when I got the 500. Presumably this is at least a doc bug, but also a product bug as it should a) not require the length and b) not give a 500 when it is not sent.

Upvotes: 0

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10126

You have to pass client UUID to the role-mappings REST method, not the ID that you specify when creating a client in admin UI. Use GET /admin/realms/{realm}/clients?clientId=realm-management REST method to find out the client UUID.

UPDATE

In Keycloak 6.0.1 to add a role it is required to pass role name and id.

Example:

POST /auth/admin/realms/{realm}/users/{user}/role-mappings/clients/{client}

[
  {
    "id": "0830ff39-43ea-48bb-af8f-696bc420c1ce",
    "name": "create-client"
  }
]

Upvotes: 22

Related Questions