private synchronized <T> T withRealm(String realmName, RealmHandler<T> consumer) throws Exception { if (keycloak == null) { keycloak = keycloakFactory.createInstance(); } RealmResource realmResource = waitForRealm(keycloak, realmName, apiTimeout); return consumer.handle(realmResource); }
private synchronized <T> T withKeycloak(KeycloakHandler<T> consumer) { if (keycloak == null) { keycloak = keycloakFactory.createInstance(); } return consumer.handle(keycloak); }
@Override public UserList listUsersWithLabels(String namespace, Map<String, String> labels) { return queryUsers( realm -> hasAttribute(realm, "namespace", namespace), user -> matchesLabels(user, labels)); }
private UserApi createUserApi(ServiceBrokerOptions options) { KeycloakFactory keycloakFactory = new KubeKeycloakFactory(client, options.getStandardAuthserviceConfigName(), options.getStandardAuthserviceCredentialsSecretName(), options.getStandardAuthserviceCertSecretName()); return new KeycloakUserApi(keycloakFactory, Clock.systemUTC()); }
@Override public UserList listAllUsersWithLabels(final Map<String, String> labels) { return queryUsers( realm -> getAttribute(realm, "namespace").isPresent(), user -> matchesLabels(user, labels)); }
/** * List users from a single namespace. */ @Override public UserList listUsers(final String namespace) { return queryUsers( realm -> hasAttribute(realm, "namespace", namespace), user -> true); }
@Override public boolean realmExists(String realmName) { return withKeycloak(kc -> getRealmResource(kc, realmName) != null); }
/** * List all users, from all namespaces. */ @Override public UserList listAllUsers() { return queryUsers( realm -> getAttribute(realm, "namespace").isPresent(), user -> true); }
private synchronized <T> T withKeycloak(Handler<T> consumer) { if (keycloak == null) { keycloak = keycloakFactory.createInstance(); } return consumer.handle(keycloak); }
@Override public Optional<User> getUserWithName(String realmName, String resourceName) throws Exception { log.info("Retrieving user {} in realm {}", resourceName, realmName); return withRealm(realmName, realm -> realm.users().list().stream() .filter(userRep -> { Map<String, List<String>> attributes = userRep.getAttributes(); return attributes != null && attributes.get("resourceName") != null && resourceName.equals(attributes.get("resourceName").get(0)); }) .findFirst() .map(userRep -> { List<GroupRepresentation> groupReps = realm.users().get(userRep.getId()).groups(); return buildUser(userRep, groupReps); })); }
private UserList queryUsers(final Predicate<RealmRepresentation> realmPredicate, final Predicate<UserRepresentation> userPredicate) { return withKeycloak(keycloak -> { List<RealmRepresentation> realmReps = keycloak.realms().findAll(); UserList userList = new UserList(); for (RealmRepresentation realmRep : realmReps) { if (realmPredicate.test(realmRep)) { String realm = realmRep.getRealm(); keycloak.realm(realm).users().list() .stream() .filter(userPredicate) .forEachOrdered(userRep -> { List<GroupRepresentation> groupReps = keycloak.realm(realm).users().get(userRep.getId()).groups(); userList.getItems().add(buildUser(userRep, groupReps)); }); } } return userList; }); }
private Optional<UserRepresentation> getUser(String realmName, String username) throws Exception { return withRealm(realmName, realm -> realm.users().search(username).stream() .filter(userRep -> username.equals(userRep.getUsername())) .findFirst()); }
/** * Test if a realm as has specific attribute. * * @param realm The realm to test. * @param attributeName The attribute to test. * @param attributeValue The expected value. May be {@code null}, in which case the attribute value * is to be expected {@code null} or not set. * @return The methods return {@code true} either if the value attributeName parameter is * {@code null} and the attribute is either missing or {@code null}, or if the attribute * value is set and equal to the parameter "attributeValue". */ static boolean hasAttribute(final RealmRepresentation realm, final String attributeName, final String attributeValue) { if (realm == null || attributeName == null) { return false; } final Optional<String> value = getAttribute(realm, attributeName); final String v = value.orElse(null); if (v == attributeValue) { // do a check on the object reference, catches "null == null" return true; } if (v == null) { // attribute value is null, but due to the previous check we know // that the required attribute value is non-null, so it doesn't match return false; } // do a proper check return v.equals(attributeValue); }
private RealmResource waitForRealm(Keycloak keycloak, String realmName, Duration timeout) throws Exception { Instant now = clock.instant(); Instant endTime = now.plus(timeout); RealmResource realmResource = null; while (now.isBefore(endTime)) { realmResource = getRealmResource(keycloak, realmName); if (realmResource != null) { break; } log.info("Waiting 1 second for realm {} to exist", realmName); Thread.sleep(1000); now = clock.instant(); } if (realmResource == null) { realmResource = getRealmResource(keycloak, realmName); } if (realmResource != null) { return realmResource; } throw new WebApplicationException("Timed out waiting for realm " + realmName + " to exist", 503); }
if (userAuthorization.getAddresses() != null && !userAuthorization.getAddresses().isEmpty()) { for (String address : userAuthorization.getAddresses()) { String groupName = operation.name() + "_" + encodePart(address);
@Override public void deleteUsers(String namespace) { withKeycloak(keycloak -> { List<RealmRepresentation> realmReps = keycloak.realms().findAll(); for (RealmRepresentation realmRep : realmReps) { String realmNs = realmRep.getAttributes().get("namespace"); if (realmNs != null && realmNs.equals(namespace)) { String realm = realmRep.getRealm(); List<UserRepresentation> userReps = keycloak.realm(realm).users().list(0, 100); while (!userReps.isEmpty()) { for (UserRepresentation userRep : userReps) { keycloak.realm(realm).users().delete(userRep.getId()); } userReps = keycloak.realm(realm).users().list(0, 100); } } } return null; }); }
@Override public Keycloak createInstance() { ConfigMap keycloakConfig = openShiftClient.configMaps().withName(keycloakConfigName).get(); Secret credentials = openShiftClient.secrets().withName(keycloakCredentialsSecretName).get(); String keycloakUri = String.format("https://%s:8443/auth", keycloakConfig.getData().get("hostname")); Base64.Decoder b64dec = Base64.getDecoder(); String adminUser = new String(b64dec.decode(credentials.getData().get("admin.username")), StandardCharsets.UTF_8); String adminPassword = new String(b64dec.decode(credentials.getData().get("admin.password")), StandardCharsets.UTF_8); log.info("User keycloak URI {}", keycloakUri); Secret certificate = openShiftClient.secrets().withName(keycloakCertSecretName).get(); KeyStore trustStore = createKeyStore(b64dec.decode(certificate.getData().get("tls.crt"))); ResteasyClient resteasyClient = new ResteasyClientBuilder() .connectTimeout(30, TimeUnit.SECONDS) .connectionPoolSize(1) .asyncExecutor(executorService) // executorService is the replacement but returns the wrong type .trustStore(trustStore) .hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY) .build(); return KeycloakBuilder.builder() .serverUrl(keycloakUri) .realm("master") .username(adminUser) .password(adminPassword) .clientId("admin-cli") .resteasyClient(resteasyClient) .build(); }
KeycloakFactory keycloakFactory = new KubeKeycloakFactory(client, keycloakConfigName, getKeycloakCredentialsSecretName(env), UserApi userApi = new KeycloakUserApi(keycloakFactory, Clock.systemUTC());
@Override public void deleteUser(String realmName, User user) throws Exception { log.info("Deleting user {} in realm {}", user.getSpec().getUsername(), realmName); withRealm(realmName, realm -> { List<UserRepresentation> users = realm.users().search(user.getSpec().getUsername()); for (UserRepresentation userRep : users) { log.info("Found user with name {}, want {}", userRep.getUsername(), user.getSpec().getUsername()); if (user.getSpec().getUsername().equals(userRep.getUsername())) { realm.users().delete(userRep.getId()); } } return users; }); }
KeycloakFactory keycloakFactory = new KubeKeycloakFactory(client, options.getStandardAuthserviceConfigName(), options.getStandardAuthserviceCredentialsSecretName(), options.getStandardAuthserviceCertSecretName()); Clock clock = Clock.systemUTC(); UserApi userApi = new KeycloakUserApi(keycloakFactory, clock, options.getUserApiTimeout());