Hi to all.
I want to create some roles via Java code. My application starts and default roles must be created.
This is my java code for check and create roles:
public static void createRoleClient(Configuration config, String roleName) throws Exception{
Keycloak keycloak = KeycloakUtility.getKeycloak(config);
RealmResource realmRes = keycloak.realm(config.getRealm());
ClientRepresentation client = realmRes.clients().findByClientId(config.getResource()).get(0);
ClientResource cliRes = realmRes.clients().get(client.getId());
RolesResource roleResource = cliRes.roles();
try {
List<RoleRepresentation> roleList = roleResource.list();
if (roleList == null || roleList.isEmpty()) {
RoleRepresentation ruoloRep = new RoleRepresentation(roleName, roleName, true);
roleResource.create(ruoloRep);
}else{
boolean exists = false;
for(RoleRepresentation r : roleList){
if(r.getName().equals(roleName)){
exists = true;
break;
}
}
if(!exists){
RoleRepresentation newRole = new RoleRepresentation(roleName, roleName, true);
roleResource.create(newRole);
}
}
} catch (NotFoundException e) {
KeycloakUtility.logoutkeycloak(config, keycloak);
throw new Exception(e);
}
KeycloakUtility.logoutkeycloak(config, keycloak);
}
It works but i would optimize it.
First question:
how does org.keycloak.admin.client.resource.RolesResource list(String search,…) methods works?
Javadocs API say
search : max number of occurrences
Search is a role’s name or a role’s id ? I’ve tryed to search it by name but it return an empty list:
roleResource.list(roleName,1,1);
Second question:
I want to create a realm level role. I call the procedure but a 403 Forbidden error is returned. I use no username and password in Configuration, only client id and secret.
How can I allow a client to register realm’s role?