javaspring-bootoauth-2.0keycloakspring-security-oauth2

Springboot Keycloak Admin add role or reset password error


I tryng to create a new user in my keycloak usint the admin client

with this code:

package br.com.fabioebner.surfpp.api.serivce;

import lombok.extern.slf4j.Slf4j;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.*;
import org.keycloak.representations.idm.*;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.Response;
import java.util.*;

@Service
@Slf4j
public class KeycloakService {
    private final RealmResource realm;
    private final Keycloak keycloak;

    public KeycloakService() {
        this.keycloak = Keycloak.getInstance(
                "https://myKey/auth/",
                "master",
                "admin",
                "myPass",
                "admin-cli");
        this.realm = keycloak.realm("myRealm");
    }

    @EventListener(ApplicationReadyEvent.class)
    public void addUser(){
        UsersResource users = realm.users();
        ClientResource api = realm.clients().get("api");
//        RoleResource usuario = api.roles().get("USUARIO");
        UserRepresentation novoUsuario = new UserRepresentation();
        novoUsuario.setUsername("joao");
        novoUsuario.setEmail("joao@s.com");
        novoUsuario.setEnabled(true);
        novoUsuario.setFirstName("Joao");
        novoUsuario.setLastName("da Silva");
        novoUsuario.setEmailVerified(true);


        Response response = users.create(novoUsuario);
        String idCriado = response.getLocation().toString().substring(response.getLocation().toString().indexOf("/users/")+7);
        updatePassword(idCriado, "1234"); //HERE RETURN 400 ERROR
        assignRealmRoles(this.realm, idCriado, Collections.singletonList("USUARIO")); //HERE RETURN 404 ERROR

        System.out.println("ss");

    }
    private void updatePassword(String id,String pass){
        CredentialRepresentation cred = new CredentialRepresentation();
        cred.setType(CredentialRepresentation.PASSWORD);
        cred.setValue(pass);
        cred.setTemporary(false);
        realm.users().get(id).resetPassword(cred);
    }
    public static void assignRealmRoles(RealmResource realm, String userId, List<String> roles) {
        String realmName = realm.toRepresentation().getRealm();

        List<RoleRepresentation> roleRepresentations = new ArrayList<>();
        for (String roleName : roles) {
            RoleRepresentation role = realm.clients().get("f3fcd887-6b7d-497b-b344-248143542202").roles().get(roleName).toRepresentation();
            roleRepresentations.add(role);
        }

        UserResource userResource = realm.users().get(userId);
        userResource.roles().clientLevel("api").add(roleRepresentations);
    }
}

So I try to create the user with the role and password without success, now the user are created but I can't add roles to that user, and update the password.


Solution

  • Update Password:

    You are getting a 400 because the user ID is invalid. Try the following:

    Response response = users.create(novoUsuario);
    String idCriado = users.list().stream()
                                .filter(user -> user.getUsername().equals("joao"))
                                .findFirst()
                                .map(UserRepresentation::getId)
                                .orElseThrow();
    updatePassword(idCriado, "1234");
    

    Add the Role

    Instead of

    userResource.roles().clientLevel("api").add(roleRepresentations);
    

    you need to pass the clientID to the clientLevel method, in your case:

    userResource.roles().clientLevel("f3fcd887-6b7d-497b-b344-248143542202").add(roleRepresentations);