Search code examples
keycloakkeycloak-rest-api

Keycloak ignores realmRoles when adding a user by rest api


When I am creating a new user by using Keycloak rest API, the application ignores the realmRoles property not assigning the role to the new user. Here is an exemple

POST: https://localhost:8543/auth/admin/realms/quarkus/users

Body:
{
   "username":"alexandre",
   "enabled":true,
   "emailVerified":true,
   "firstName":"Alexandre",
   "lastName":"Oliveira",
   "email":"alexandreqogmailcom",
   "credentials":[
      {
         "type":"password",
         "value":"123456",
         "temporary":false
      }
   ],
   "realmRoles":[
      "user_esc"
   ],
   "access":{
      "mapRoles":true
   }

Is there a way to resolve this problem or a work around ?

PS: I am using the keycloak version 12.0.1


Solution

  • If you are expecting that with the endpoint:

    POST: https://localhost:8543/auth/admin/realms/quarkus/users
    

    it will also create the realm roles, that will not happen, it will not create the Realm roles. To create the Realm roles you either use the Admin Console or you use the endpoint:

    POST https://localhost:8543/auth/admin/realms/quarkus/roles
    

    with the payload

    {"name":"<ROLE_NAME>","description":"<DESCRIPTION>"}

    if it is a non Composite Realm Role.

    To assign the Realm Role to the user, after having create the user, call the endpoint:

    POST: https://localhost:8543/auth/admin/realms/quarkus/users/<USER_ID>/role-mappings/realm
    

    with the payload

    [{"id":"<Role ID>","name":"<Role Name>"}] 
    

    The role ID you can get it from:

    GET: https://localhost:8543/auth/admin/realms/quarkus/roles/<ROLE_NAME>
    

    and the user ID from :

    GET: https://localhost:8543/auth/admin/realms/quarkus/users/?username=<USERNAME>
    

    I have upload the following bash scripts to automatize this process.