rocket_moon
rocket_moon

Reputation: 309

When Creating a new user set realmRoles - Keycloak Admin REST API

I'm having a problem when assigning already existing realm roles when creating a user. Following the documentation when creating a new user POST /{realm}/users, in the body parameter using the UserRepresentation, we have field called realmRoles which is optional. I already tried to assign in the follow Schemas:

[
    {
        "id": "123asd-3223r-wer23rwer-werwer",
        "name": "name-of-role-1"
    },
    {
        "id": "23wedf-wefwcs-dfsdf-sdf",
        "name": "name-of-role-2"
    }
]
[
    {
        "id": "123asd-3223r-wer23rwer-werwer",
    },
    {
        "id": "23wedf-wefwcs-dfsdf-sdf",
    }
]
[ "123asd-3223r-wer23rwer-werwer","23wedf-wefwcs-dfsdf-sdf"]
[ "name-of-role-1","name-of-role-2"]

No of the above work. Either they are ignore, or I get an unknown error.

Upvotes: 2

Views: 5629

Answers (1)

Bench Vue
Bench Vue

Reputation: 9300

You needs to use user's role mapping API instead of user API

POST {keycloak URL}/admin/realms/{my_realm}/users/{user-id}/role-mappings/realm

body of POST

[
  {
    "id": {realm_role_id},
    "name": {realm_role_name},
    "composite": false,
    "clientRole": false,
    "containerId": {my_realm_id}
  }
]

Detail information is official Admin API at Add realm-level role mappings to the user section.

enter image description here

Demo by Postman

1 Get master access token, assign token environment variable

here is more detail how to get master token

enter image description here

2 Get Users list by #1 token

enter image description here

3 Get user with #2 {user id}

enter image description here

4 Get Realm ID with #1 token

enter image description here

5 Get realm's roles list

enter image description here

6 Set user's realm role mapping with #5's realm role

enter image description here

In the body, use array format - it means can assign with multiple realm roles

POST URL

http://localhost:8180/auth/admin/realms/test/users/f3d78ca2-7bab-4aed-b1a4-8b98bf1be000/role-mappings/realm

containerId is #4's {realm_id}

id is #5 {role_id}

[
  {
    "id": "b73643c4-5375-4f9d-b6d5-65dc7c719c68",
    "name": "name-of-role-2",
    "composite": false,
    "clientRole": false,
    "containerId": "a6d347b4-3fe8-4410-bda6-54dbf8e50903"
  }
]

Return status should be 204 No Content.

If not, something thing wrong.

Finally, you can confirm that realm role assigned result.

enter image description here

If you want to confirm by API

GET API

http://localhost:8180/auth/admin/realms/test/users/f3d78ca2-7bab-4aed-b1a4-8b98bf1be000/role-mappings/realm

enter image description here

Upvotes: 8

Related Questions