0

i was trying a code to upload all users to keycloak user list and it works well. i used an excel file to read then push each row into keycloak field but i was thinking to add roles to each user at the same time. when i try out this code it says role field does not exist in user and gives me error

this is my code

Read From Excel and store in an array

let path = 'http://localhost:8080/auth/admin/realms/msportal';
let _userTobeCreated = ReadFromExcel('./uploads/employees-roles.xlsx');

function ReadFromExcel(filename) {
    let userTobeCreated = []

    xlsxFile(filename).then((rows) => {
        rows.forEach(row => {
            let userObject = {
                username: row[0],
                lastName: row[1],
                firstName: row[2],
                email: row[3],
                roles: row[4].split(',')

            }
            userTobeCreated.push(userObject);

        });
    })
    return userTobeCreated;

}

create function

function CreateKCBulkUser(user) {
  let urlCreateUser = `${path}/users`;
  return axios({

    method: 'post',
    url: urlCreateUser,
    data: JSON.stringify(user),
    headers: {
      'content-type': 'application/json',
      'Authorization': `Bearer ${kc_accessToken}`
    }

  })
    .then(function (response) {
      console.log("User created!!");
      _userlists = response.data;

    })
    .catch(function (error) {
      console.log(error);
    });
}

Calling Function

   _usersToBeCreated.forEach((v)=>{
        CreateKCBulkUser(v);
      })

excel file

enter image description here

1 Answers1

0

Role is not a part of user entity. First you must create role entity and then you need to create role-mapping. See API doc.

BTW: role is vague definition, because Keycloak has real roles/client roles + I would use keycloak-nodejs-admin-client instead of plain axios requests.

Jan Garaj
  • 25,598
  • 3
  • 38
  • 59