Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak: how to add/update user with roles programmatically?

Tags:

java

keycloak

I am trying to update a user, with admin role, for the realm using admin console, but it's not working.

My code:

UserResource use = userResources.get(search.get(0).getId());
use.resetPassword(credentials);

user=use.toRepresentation();
List<String> roles=new ArrayList<String>();
roles.add("realm-admin");
Map<String,List<String>> m= new HashMap<String,List<String>>();

m.put("realm-management",roles);
user.setClientRoles(m);
use.update(user);

Any idea what I might be doing wrong?

like image 539
Carlos Tomás Avatar asked Apr 04 '16 14:04

Carlos Tomás


People also ask

How to map a custom role in keykeycloak?

Keycloak provides a custom interface for each of the social identity providers. It eases our development efforts and one needs to only configure the required secrets or API keys. To map the custom role, go to identity providers section and click Editbutton

How to manage Keycloak configurations programmatically?

On a more general level when you manage Keycloak configurations programmatically you have two options: kcadm.sh: this is a command-line wrapper that drives the Keycloak Admin REST API. This approach is used by puppet-module-keycloak.

How do I add a new role to my client?

Switch to the realm of your client. Click on your client ID from the list of ‘clients’ that you can see when clicking on Clients button in the left side navigation bar. In the next screen switch to ‘Roles’ tab and click on ‘Add Role’ button. In the next screen, give the name of you role and description (optional) and click on save.

Which user can access /member API in Keycloak?

According to our KeyCloak Security Configuration class, the user with the role Member can access /member API, and the user with the role Admin can access /admin API. Let’s test our application using Postman.


1 Answers

UserResource use = userResources.get(idUser);

use.roles().clientLevel(id).add(use.roles().clientLevel( 
id).listAvailable());

This is the solution I found the id is the id of the client and not the client_id.

like image 136
Carlos Tomás Avatar answered Nov 15 '22 17:11

Carlos Tomás