Creating User With Client Role Not Working

Hello Forum!

I am struggling to create a user with a client role. My client is called client_interface.
Below you see my java code! It seems to not create a client nor a realm user so in total it’s doing nothing and I don’t know why.
ANY idea?

public UserRepresentation createKeycloakUser(Student student) {
		this.roleMapping.put(this.clientId, Collections.singletonList("web-user"));
		Keycloak adminKeycloak = getAdminKeycloak();
		CredentialRepresentation cr = new CredentialRepresentation();
		cr.setType("password");
		cr.setValue(student.getPassword());

		UserRepresentation userRepresentation = new UserRepresentation();
		userRepresentation.setUsername(student.getUsername());
		userRepresentation.setClientRoles(roleMapping);
		userRepresentation.setCredentials(Collections.singletonList(cr));
		userRepresentation.setEnabled(true);

		adminKeycloak.realm(realm).users().create(userRepresentation);
		List<UserRepresentation> userList = adminKeycloak.realm(realm).users().search(student.getUsername()).stream()
			.filter(userRep -> userRep.getUsername().equals(student.getUsername())).collect(Collectors.toList());
		userRepresentation = userList.get(0);
		logger.info("User with id: " + userRepresentation.getId() +" created");
		return userRepresentation;
	}

This is a known issue. You need to do this in multiple steps.

Do you have a link / tutorial for that?
@vju42

Sorry I missed your message. You just need to create the user object. There are APIs to add the roles and you need role ids (not names) which you need to look up potentially first.

@vju42

Added a method but getting a 404 on the marked part, no idea why ;(

private void assignRoleToUser(String userId, String role){
        Keycloak keycloak = getAdminKeycloak();
        UsersResource usersResource = keycloak.realm(realm).users();
        UserResource userResource = usersResource.get(userId);
        ClientResource clientResource =keycloak.realm(realm).clients().get(clientId);
        RoleRepresentation clientRole = clientResource.roles().get(role).toRepresentation(); //<-- here
        userResource.roles().clientLevel(clientId).add(Collections.singletonList(clientRole));
    }

@vju42
Seems rolesRessource throws a 404

Keycloaks api design is just confusing, finally overcame this challenge and set up a github gist:

I’m sorry we only used the admin rest api. We had to get the id of the role by name and then use PUT to add the json structure for roles as defined in user representation.

Ah, just remembered: there is a shortcut.
Define a group and assign the role to the group. It may end with one group per role.

Then simply add a user to the group.

The code works just fine. After redeployment i get error 401 and forgot what roles i need to set, do you remember where i could look this up?

greetings