KEYCLOAK-14549 Make ClientProvider independent of RealmProvider

Co-Authored-By: vramik <vramik@redhat.com>
This commit is contained in:
Hynek Mlnarik 2020-06-22 22:23:40 +02:00 committed by Hynek Mlnařík
parent ac0011ab6f
commit c566b46e8f
63 changed files with 656 additions and 323 deletions

View file

@ -49,3 +49,26 @@ jobs:
run: mvn clean install -B -Pauth-server-wildfly -DskipTests -f testsuite/pom.xml
- name: Run base tests
run: mvn clean install -B -Pauth-server-wildfly -f testsuite/integration-arquillian/tests/base/pom.xml | misc/log/trimmer.sh; exit ${PIPESTATUS[0]}
test-undertow-map:
name: Test undertow - map provider
needs: build
runs-on: ubuntu-latest
env:
MAVEN_OPTS: -Xmx2048m
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Download Maven Repo
uses: actions/download-artifact@v1
with:
name: maven-repo
path: .
- name: Extract Maven Repo
shell: bash
run: tar -xzvf maven-repo.tgz -C ~
- name: Build testsuite
run: mvn clean install -B -DskipTests -f testsuite/pom.xml
- name: Run base tests - undertow
run: mvn clean install -B -f testsuite/integration-arquillian/tests/base/pom.xml -Dkeycloak.client.provider=map | misc/log/trimmer.sh; exit ${PIPESTATUS[0]}

View file

@ -68,10 +68,10 @@ public interface RoleByIdResource {
@Produces(MediaType.APPLICATION_JSON)
Set<RoleRepresentation> getRealmRoleComposites(@PathParam("role-id") String id);
@Path("{role-id}/composites/clients/{client}")
@Path("{role-id}/composites/clients/{clientUuid}")
@GET
@Produces(MediaType.APPLICATION_JSON)
Set<RoleRepresentation> getClientRoleComposites(@PathParam("role-id") String id, @PathParam("client") String client);
Set<RoleRepresentation> getClientRoleComposites(@PathParam("role-id") String id, @PathParam("clientUuid") String clientUuid);
@Path("{role-id}/composites")
@DELETE

View file

@ -87,9 +87,9 @@ public interface RoleResource {
Set<RoleRepresentation> getRealmRoleComposites();
@GET
@Path("composites/clients/{appName}")
@Path("composites/clients/{clientUuid}")
@Produces(MediaType.APPLICATION_JSON)
Set<RoleRepresentation> getClientRoleComposites(@PathParam("appName") String appName);
Set<RoleRepresentation> getClientRoleComposites(@PathParam("clientUuid") String clientUuid);
@POST
@Path("composites")

View file

@ -32,6 +32,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -53,7 +54,7 @@ public class ClientAdapter implements ClientModel, CachedObject {
private void getDelegateForUpdate() {
if (updated == null) {
cacheSession.registerClientInvalidation(cached.getId(), cached.getClientId(), cachedRealm.getId());
updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm);
updated = cacheSession.getClientDelegate().getClientById(cachedRealm, cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
}
}
@ -65,7 +66,7 @@ public class ClientAdapter implements ClientModel, CachedObject {
protected boolean isUpdated() {
if (updated != null) return true;
if (!invalidated) return false;
updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm);
updated = cacheSession.getClientDelegate().getClientById(cachedRealm, cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
return true;
}
@ -253,14 +254,10 @@ public class ClientAdapter implements ClientModel, CachedObject {
}
public Set<RoleModel> getScopeMappings() {
if (isUpdated()) return updated.getScopeMappings();
Set<RoleModel> roles = new HashSet<>();
for (String id : cached.getScope()) {
roles.add(cacheSession.getRoleById(id, getRealm()));
}
return roles;
public Stream<RoleModel> getScopeMappingsStream() {
if (isUpdated()) return updated.getScopeMappingsStream();
return cached.getScope().stream()
.map(id -> cacheSession.getRoleById(id, cachedRealm));
}
public void addScopeMapping(RoleModel role) {

View file

@ -28,6 +28,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -156,14 +157,10 @@ public class ClientScopeAdapter implements ClientScopeModel {
updated.setProtocol(protocol);
}
public Set<RoleModel> getScopeMappings() {
if (isUpdated()) return updated.getScopeMappings();
Set<RoleModel> roles = new HashSet<>();
for (String id : cached.getScope()) {
roles.add(cacheSession.getRoleById(id, getRealm()));
}
return roles;
public Stream<RoleModel> getScopeMappingsStream() {
if (isUpdated()) return updated.getScopeMappingsStream();
return cached.getScope().stream()
.map(id -> cacheSession.getRoleById(id, cachedRealm));
}
public void addScopeMapping(RoleModel role) {

View file

@ -776,23 +776,23 @@ public class RealmAdapter implements CachedRealmModel {
@Override
public boolean removeClient(String id) {
return cacheSession.removeClient(id, this);
return cacheSession.removeClient(this, id);
}
@Override
public ClientModel getClientById(String id) {
if (isUpdated()) return updated.getClientById(id);
return cacheSession.getClientById(id, this);
return cacheSession.getClientById(this, id);
}
@Override
public ClientModel getClientByClientId(String clientId) {
return cacheSession.getClientByClientId(clientId, this);
return cacheSession.getClientByClientId(this, clientId);
}
@Override
public List<ClientModel> searchClientByClientId(String clientId, Integer firstResult, Integer maxResults) {
return cacheSession.searchClientsByClientId(clientId, firstResult, maxResults, this);
return cacheSession.searchClientsByClientId(this, clientId, firstResult, maxResults);
}
@Override

View file

@ -482,6 +482,7 @@ public class RealmCacheSession implements CacheRealmProvider {
RealmModel realm = getRealm(id);
if (realm == null) return false;
listInvalidations.add(id);
evictRealmOnRemoval(realm);
return getRealmDelegate().removeRealm(id);
}
@ -495,13 +496,13 @@ public class RealmCacheSession implements CacheRealmProvider {
@Override
public ClientModel addClient(RealmModel realm, String clientId) {
ClientModel client = getRealmDelegate().addClient(realm, clientId);
ClientModel client = getClientDelegate().addClient(realm, clientId);
return addedClient(realm, client);
}
@Override
public ClientModel addClient(RealmModel realm, String id, String clientId) {
ClientModel client = getRealmDelegate().addClient(realm, id, clientId);
ClientModel client = getClientDelegate().addClient(realm, id, clientId);
return addedClient(realm, client);
}
@ -552,8 +553,13 @@ public class RealmCacheSession implements CacheRealmProvider {
}
@Override
public boolean removeClient(String id, RealmModel realm) {
ClientModel client = getClientById(id, realm);
public void removeClients(RealmModel realm) {
getClientDelegate().removeClients(realm);
}
@Override
public boolean removeClient(RealmModel realm, String id) {
ClientModel client = getClientById(realm, id);
if (client == null) return false;
invalidateClient(client.getId());
@ -575,7 +581,7 @@ public class RealmCacheSession implements CacheRealmProvider {
}
}
return getRealmDelegate().removeClient(id, realm);
return getClientDelegate().removeClient(realm, id);
}
@ -636,7 +642,7 @@ public class RealmCacheSession implements CacheRealmProvider {
@Override
public Set<RoleModel> getClientRoles(RealmModel realm, ClientModel client) {
String cacheKey = getRolesCacheKey(client.getId());
boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId());
boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId()) || listInvalidations.contains(realm.getId());
if (queryDB) {
return getRealmDelegate().getClientRoles(realm, client);
}
@ -735,7 +741,7 @@ public class RealmCacheSession implements CacheRealmProvider {
@Override
public RoleModel getClientRole(RealmModel realm, ClientModel client, String name) {
String cacheKey = getRoleByNameCacheKey(client.getId(), name);
boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId());
boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId()) || listInvalidations.contains(realm.getId());
if (queryDB) {
return getRealmDelegate().getClientRole(realm, client, name);
}
@ -882,8 +888,8 @@ public class RealmCacheSession implements CacheRealmProvider {
}
@Override
public Long getClientsCount(RealmModel realm) {
return getRealmDelegate().getClientsCount(realm);
public long getClientsCount(RealmModel realm) {
return getClientDelegate().getClientsCount(realm);
}
@Override
@ -1035,24 +1041,26 @@ public class RealmCacheSession implements CacheRealmProvider {
}
@Override
public ClientModel getClientById(String id, RealmModel realm) {
public ClientModel getClientById(RealmModel realm, String id) {
CachedClient cached = cache.get(id, CachedClient.class);
if (cached != null && !cached.getRealm().equals(realm.getId())) {
cached = null;
}
boolean queryDB = invalidations.contains(id) || listInvalidations.contains(realm.getId());
if (queryDB) { // short-circuit if the client has been potentially invalidated
return getClientDelegate().getClientById(realm, id);
}
if (cached != null) {
logger.tracev("client by id cache hit: {0}", cached.getClientId());
}
if (cached == null) {
Long loaded = cache.getCurrentRevision(id);
ClientModel model = getClientDelegate().getClientById(id, realm);
ClientModel model = getClientDelegate().getClientById(realm, id);
if (model == null) return null;
ClientModel adapter = cacheClient(realm, model, loaded);
managedApplications.put(id, adapter);
return adapter;
} else if (invalidations.contains(id)) {
return getRealmDelegate().getClientById(id, realm);
} else if (managedApplications.containsKey(id)) {
return managedApplications.get(id);
}
@ -1111,7 +1119,7 @@ public class RealmCacheSession implements CacheRealmProvider {
// its also hard to test stuff
if (model.shouldInvalidate(cached)) {
registerClientInvalidation(cached.getId(), cached.getClientId(), realm.getId());
return getClientDelegate().getClientById(cached.getId(), realm);
return getClientDelegate().getClientById(realm, cached.getId());
}
}
ClientAdapter adapter = new ClientAdapter(realm, cached, this);
@ -1120,38 +1128,40 @@ public class RealmCacheSession implements CacheRealmProvider {
}
@Override
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
return getClientDelegate().searchClientsByClientId(clientId, firstResult, maxResults, realm);
public List<ClientModel> searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) {
return getClientDelegate().searchClientsByClientId(realm, clientId, firstResult, maxResults);
}
@Override
public ClientModel getClientByClientId(String clientId, RealmModel realm) {
public ClientModel getClientByClientId(RealmModel realm, String clientId) {
String cacheKey = getClientByClientIdCacheKey(clientId, realm.getId());
ClientListQuery query = cache.get(cacheKey, ClientListQuery.class);
String id = null;
boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
if (queryDB) { // short-circuit if the client has been potentially invalidated
return getClientDelegate().getClientByClientId(realm, clientId);
}
if (query != null) {
logger.tracev("client by name cache hit: {0}", clientId);
}
if (query == null) {
Long loaded = cache.getCurrentRevision(cacheKey);
ClientModel model = getClientDelegate().getClientByClientId(clientId, realm);
ClientModel model = getClientDelegate().getClientByClientId(realm, clientId);
if (model == null) return null;
if (invalidations.contains(model.getId())) return model;
id = model.getId();
query = new ClientListQuery(loaded, cacheKey, realm, id);
logger.tracev("adding client by name cache miss: {0}", clientId);
cache.addRevisioned(query, startupRevision);
} else if (invalidations.contains(cacheKey)) {
return getClientDelegate().getClientByClientId(clientId, realm);
} else {
id = query.getClients().iterator().next();
if (invalidations.contains(id)) {
return getClientDelegate().getClientByClientId(clientId, realm);
return getClientDelegate().getClientByClientId(realm, clientId);
}
}
return getClientById(id, realm);
return getClientById(realm, id);
}
static String getClientByClientIdCacheKey(String clientId, String realmId) {

View file

@ -737,7 +737,7 @@ public class UserCacheSession implements UserCache {
}
private UserConsentModel toConsentModel(RealmModel realm, CachedUserConsent cachedConsent) {
ClientModel client = session.realms().getClientById(cachedConsent.getClientDbId(), realm);
ClientModel client = session.clients().getClientById(realm, cachedConsent.getClientDbId());
if (client == null) {
return null;
}

View file

@ -46,7 +46,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -255,12 +255,11 @@ public class ClientAdapter implements ClientModel, JpaModel<ClientEntity> {
}
@Override
public Set<RoleModel> getScopeMappings() {
public Stream<RoleModel> getScopeMappingsStream() {
return getEntity().getScopeMapping().stream()
.map(RoleEntity::getId)
.map(realm::getRoleById)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
.filter(Objects::nonNull);
}
@Override

View file

@ -37,7 +37,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -227,12 +227,11 @@ public class ClientScopeAdapter implements ClientScopeModel, JpaModel<ClientScop
}
@Override
public Set<RoleModel> getScopeMappings() {
public Stream<RoleModel> getScopeMappingsStream() {
return getEntity().getScopeMapping().stream()
.map(RoleEntity::getId)
.map(realm::getRoleById)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
.filter(Objects::nonNull);
}
@Override

View file

@ -0,0 +1,55 @@
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models.jpa;
import org.keycloak.Config;
import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.ClientProvider;
import org.keycloak.models.ClientProviderFactory;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import javax.persistence.EntityManager;
public class JpaClientProviderFactory implements ClientProviderFactory {
@Override
public void init(Config.Scope config) {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
@Override
public String getId() {
return "jpa";
}
@Override
public ClientProvider create(KeycloakSession session) {
EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager();
return new JpaRealmProvider(session, em);
}
@Override
public void close() {
}
}

View file

@ -23,6 +23,7 @@ import org.keycloak.connections.jpa.util.JpaUtils;
import org.keycloak.migration.MigrationModel;
import org.keycloak.models.ClientInitialAccessModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientProvider;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
@ -46,13 +47,14 @@ import javax.persistence.TypedQuery;
import java.util.*;
import java.util.stream.Collectors;
import org.keycloak.models.ModelException;
import static org.keycloak.common.util.StackUtil.getShortStackTrace;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JpaRealmProvider implements RealmProvider {
public class JpaRealmProvider implements RealmProvider, ClientProvider {
protected static final Logger logger = Logger.getLogger(JpaRealmProvider.class);
private final KeycloakSession session;
protected EntityManager em;
@ -152,13 +154,7 @@ public class JpaRealmProvider implements RealmProvider {
int num = em.createNamedQuery("deleteGroupRoleMappingsByRealm")
.setParameter("realm", realm.getId()).executeUpdate();
TypedQuery<String> query = em.createNamedQuery("getClientIdsByRealm", String.class);
query.setParameter("realm", realm.getId());
List<String> clients = query.getResultList();
for (String client : clients) {
// No need to go through cache. Clients were already invalidated
removeClient(client, adapter);
}
session.clients().removeClients(adapter);
num = em.createNamedQuery("deleteDefaultClientScopeRealmMappingByRealm")
.setParameter("realm", realm).executeUpdate();
@ -245,11 +241,10 @@ public class JpaRealmProvider implements RealmProvider {
if (getClientRole(realm, client, name) != null) {
throw new ModelDuplicateException();
}
ClientEntity clientEntity = em.getReference(ClientEntity.class, client.getId());
RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(id);
roleEntity.setName(name);
roleEntity.setClient(clientEntity);
roleEntity.setClientId(client.getId());
roleEntity.setClientRole(true);
roleEntity.setRealmId(realm.getId());
em.persist(roleEntity);
@ -450,10 +445,11 @@ public class JpaRealmProvider implements RealmProvider {
}
@Override
public Long getClientsCount(RealmModel realm) {
return em.createNamedQuery("getRealmClientsCount", Long.class)
public long getClientsCount(RealmModel realm) {
final Long res = em.createNamedQuery("getRealmClientsCount", Long.class)
.setParameter("realm", realm.getId())
.getSingleResult();
return res == null ? 0l : res;
}
@Override
@ -593,6 +589,9 @@ public class JpaRealmProvider implements RealmProvider {
if (clientId == null) {
clientId = id;
}
logger.tracef("addClient(%s, %s, %s)%s", realm, id, clientId, getShortStackTrace());
ClientEntity entity = new ClientEntity();
entity.setId(id);
entity.setClientId(clientId);
@ -628,17 +627,12 @@ public class JpaRealmProvider implements RealmProvider {
if (clients.isEmpty()) return Collections.EMPTY_LIST;
List<ClientModel> list = new LinkedList<>();
for (String id : clients) {
ClientModel client = session.realms().getClientById(id, realm);
ClientModel client = session.clients().getClientById(realm, id);
if (client != null) list.add(client);
}
return Collections.unmodifiableList(list);
}
@Override
public List<ClientModel> getClients(RealmModel realm) {
return this.getClients(realm, null, null);
}
@Override
public List<ClientModel> getAlwaysDisplayInConsoleClients(RealmModel realm) {
TypedQuery<String> query = em.createNamedQuery("getAlwaysDisplayInConsoleClients", String.class);
@ -647,14 +641,16 @@ public class JpaRealmProvider implements RealmProvider {
if (clients.isEmpty()) return Collections.EMPTY_LIST;
List<ClientModel> list = new LinkedList<>();
for (String id : clients) {
ClientModel client = session.realms().getClientById(id, realm);
ClientModel client = session.clients().getClientById(realm, id);
if (client != null) list.add(client);
}
return Collections.unmodifiableList(list);
}
@Override
public ClientModel getClientById(String id, RealmModel realm) {
public ClientModel getClientById(RealmModel realm, String id) {
logger.tracef("getClientById(%s, %s)%s", realm, id, getShortStackTrace());
ClientEntity app = em.find(ClientEntity.class, id);
// Check if application belongs to this realm
if (app == null || !realm.getId().equals(app.getRealm().getId())) return null;
@ -664,18 +660,20 @@ public class JpaRealmProvider implements RealmProvider {
}
@Override
public ClientModel getClientByClientId(String clientId, RealmModel realm) {
public ClientModel getClientByClientId(RealmModel realm, String clientId) {
logger.tracef("getClientByClientId(%s, %s)%s", realm, clientId, getShortStackTrace());
TypedQuery<String> query = em.createNamedQuery("findClientIdByClientId", String.class);
query.setParameter("clientId", clientId);
query.setParameter("realm", realm.getId());
List<String> results = query.getResultList();
if (results.isEmpty()) return null;
String id = results.get(0);
return session.realms().getClientById(id, realm);
return session.clients().getClientById(realm, id);
}
@Override
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
public List<ClientModel> searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) {
TypedQuery<String> query = em.createNamedQuery("searchClientsByClientId", String.class);
if (firstResult != null && firstResult > 0) {
query.setFirstResult(firstResult);
@ -687,12 +685,26 @@ public class JpaRealmProvider implements RealmProvider {
query.setParameter("realm", realm.getId());
List<String> results = query.getResultList();
if (results.isEmpty()) return Collections.EMPTY_LIST;
return results.stream().map(id -> session.realms().getClientById(id, realm)).collect(Collectors.toList());
return results.stream().map(id -> session.clients().getClientById(realm, id)).collect(Collectors.toList());
}
@Override
public boolean removeClient(String id, RealmModel realm) {
final ClientModel client = getClientById(id, realm);
public void removeClients(RealmModel realm) {
TypedQuery<String> query = em.createNamedQuery("getClientIdsByRealm", String.class);
query.setParameter("realm", realm.getId());
List<String> clients = query.getResultList();
for (String client : clients) {
// No need to go through cache. Clients were already invalidated
removeClient(realm, client);
}
}
@Override
public boolean removeClient(RealmModel realm, String id) {
logger.tracef("removeClient(%s, %s)%s", realm, id, getShortStackTrace());
final ClientModel client = getClientById(realm, id);
if (client == null) return false;
session.users().preRemove(realm, client);

View file

@ -17,6 +17,7 @@
package org.keycloak.models.jpa;
import org.keycloak.Config;
import org.jboss.logging.Logger;
import org.keycloak.common.enums.SslRequired;
import org.keycloak.common.util.MultivaluedHashMap;
@ -829,27 +830,27 @@ public class RealmAdapter implements RealmModel, JpaModel<RealmEntity> {
}
@Override
public List<ClientModel> getClients() {
return session.realms().getClients(this);
return session.clients().getClients(this);
}
@Override
public List<ClientModel> getClients(Integer firstResult, Integer maxResults) {
return session.realms().getClients(this, firstResult, maxResults);
return session.clients().getClients(this, firstResult, maxResults);
}
@Override
public List<ClientModel> getAlwaysDisplayInConsoleClients() {
return session.realms().getAlwaysDisplayInConsoleClients(this);
return session.clients().getAlwaysDisplayInConsoleClients(this);
}
@Override
public ClientModel addClient(String name) {
return session.realms().addClient(this, name);
return session.clients().addClient(this, name);
}
@Override
public ClientModel addClient(String id, String clientId) {
return session.realms().addClient(this, id, clientId);
return session.clients().addClient(this, id, clientId);
}
@Override
@ -857,22 +858,22 @@ public class RealmAdapter implements RealmModel, JpaModel<RealmEntity> {
if (id == null) return false;
ClientModel client = getClientById(id);
if (client == null) return false;
return session.realms().removeClient(id, this);
return session.clients().removeClient(this, id);
}
@Override
public ClientModel getClientById(String id) {
return session.realms().getClientById(id, this);
return session.clients().getClientById(this, id);
}
@Override
public ClientModel getClientByClientId(String clientId) {
return session.realms().getClientByClientId(clientId, this);
return session.clients().getClientByClientId(this, clientId);
}
@Override
public List<ClientModel> searchClientByClientId(String clientId, Integer firstResult, Integer maxResults) {
return session.realms().searchClientsByClientId(clientId, firstResult, maxResults, this);
return session.clients().searchClientsByClientId(this, clientId, firstResult, maxResults);
}
private static final String BROWSER_HEADER_PREFIX = "_browser_header.";
@ -1253,18 +1254,10 @@ public class RealmAdapter implements RealmModel, JpaModel<RealmEntity> {
if (masterAdminClientId == null) {
return null;
}
ClientEntity masterAdminClient = em.find(ClientEntity.class, masterAdminClientId);
if (masterAdminClient == null) {
return null;
}
RealmModel masterRealm = null;
String masterAdminClientRealmId = masterAdminClient.getRealm().getId();
if (masterAdminClientRealmId.equals(getId())) {
masterRealm = this;
} else {
masterRealm = session.realms().getRealm(masterAdminClientRealmId);
}
return session.realms().getClientById(masterAdminClient.getId(), masterRealm);
RealmModel masterRealm = getName().equals(Config.getAdminRealm())
? this
: session.realms().getRealm(Config.getAdminRealm());
return session.clients().getClientById(masterRealm, masterAdminClientId);
}
@Override

View file

@ -202,7 +202,7 @@ public class RoleAdapter implements RoleModel, JpaModel<RoleEntity> {
@Override
public String getContainerId() {
if (isClientRole()) return role.getClient().getId();
if (isClientRole()) return role.getClientId();
else return realm.getId();
}
@ -210,7 +210,7 @@ public class RoleAdapter implements RoleModel, JpaModel<RoleEntity> {
@Override
public RoleContainerModel getContainer() {
if (role.isClientRole()) {
return realm.getClientById(role.getClient().getId());
return realm.getClientById(role.getClientId());
} else {
return realm;

View file

@ -55,11 +55,11 @@ import java.util.Set;
@UniqueConstraint(columnNames = { "NAME", "CLIENT_REALM_CONSTRAINT" })
})
@NamedQueries({
@NamedQuery(name="getClientRoles", query="select role from RoleEntity role where role.client.id = :client order by role.name"),
@NamedQuery(name="getClientRoleIds", query="select role.id from RoleEntity role where role.client.id = :client"),
@NamedQuery(name="getClientRoleByName", query="select role from RoleEntity role where role.name = :name and role.client = :client"),
@NamedQuery(name="getClientRoleIdByName", query="select role.id from RoleEntity role where role.name = :name and role.client.id = :client"),
@NamedQuery(name="searchForClientRoles", query="select role from RoleEntity role where role.client.id = :client and ( lower(role.name) like :search or lower(role.description) like :search ) order by role.name"),
@NamedQuery(name="getClientRoles", query="select role from RoleEntity role where role.clientId = :client order by role.name"),
@NamedQuery(name="getClientRoleIds", query="select role.id from RoleEntity role where role.clientId = :client"),
@NamedQuery(name="getClientRoleByName", query="select role from RoleEntity role where role.name = :name and role.clientId = :client"),
@NamedQuery(name="getClientRoleIdByName", query="select role.id from RoleEntity role where role.name = :name and role.clientId = :client"),
@NamedQuery(name="searchForClientRoles", query="select role from RoleEntity role where role.clientId = :client and ( lower(role.name) like :search or lower(role.description) like :search ) order by role.name"),
@NamedQuery(name="getRealmRoles", query="select role from RoleEntity role where role.clientRole = false and role.realm.id = :realm order by role.name"),
@NamedQuery(name="getRealmRoleIds", query="select role.id from RoleEntity role where role.clientRole = false and role.realm.id = :realm"),
@NamedQuery(name="getRealmRoleByName", query="select role from RoleEntity role where role.clientRole = false and role.name = :name and role.realm = :realm"),
@ -91,9 +91,8 @@ public class RoleEntity {
@Column(name="CLIENT_ROLE")
private boolean clientRole;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CLIENT")
private ClientEntity client;
@Column(name="CLIENT")
private String clientId;
// Hack to ensure that either name+client or name+realm are unique. Needed due to MS-SQL as it don't allow multiple NULL values in the column, which is part of constraint
@Column(name="CLIENT_REALM_CONSTRAINT", length = 36)
@ -179,15 +178,13 @@ public class RoleEntity {
this.clientRealmConstraint = realm.getId();
}
public ClientEntity getClient() {
return client;
public String getClientId() {
return clientId;
}
public void setClient(ClientEntity client) {
this.client = client;
if (client != null) {
this.clientRealmConstraint = client.getId();
}
public void setClientId(String clientId) {
this.clientId = clientId;
this.clientRealmConstraint = clientId;
}
public String getClientRealmConstraint() {

View file

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
~ * Copyright 2020 Red Hat, Inc. and/or its affiliates
~ * and other contributors as indicated by the @author tags.
~ *
~ * Licensed under the Apache License, Version 2.0 (the "License");
~ * you may not use this file except in compliance with the License.
~ * You may obtain a copy of the License at
~ *
~ * http://www.apache.org/licenses/LICENSE-2.0
~ *
~ * Unless required by applicable law or agreed to in writing, software
~ * distributed under the License is distributed on an "AS IS" BASIS,
~ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ * See the License for the specific language governing permissions and
~ * limitations under the License.
-->
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="keycloak" id="map-remove-ri">
<dropForeignKeyConstraint baseTableName="REALM" constraintName="FK_TRAF444KK6QRKMS7N56AIWQ5Y"/>
<dropForeignKeyConstraint baseTableName="KEYCLOAK_ROLE" constraintName="FK_KJHO5LE2C0RAL09FL8CM9WFW9"/>
</changeSet>
</databaseChangeLog>

View file

@ -66,4 +66,6 @@
<include file="META-INF/jpa-changelog-8.0.0.xml"/>
<include file="META-INF/jpa-changelog-9.0.0.xml"/>
<include file="META-INF/jpa-changelog-9.0.1.xml"/>
<include file="META-INF/jpa-changelog-11.0.0.xml"/>
</databaseChangeLog>

View file

@ -0,0 +1,18 @@
#
# Copyright 2020 Red Hat, Inc. and/or its affiliates
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
org.keycloak.models.jpa.JpaClientProviderFactory

View file

@ -17,13 +17,14 @@
package org.keycloak.models.cache;
import org.keycloak.models.ClientProvider;
import org.keycloak.models.RealmProvider;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface CacheRealmProvider extends RealmProvider {
public interface CacheRealmProvider extends RealmProvider, ClientProvider {
void clear();
RealmProvider getRealmDelegate();

View file

@ -20,30 +20,92 @@ import org.keycloak.provider.Provider;
import org.keycloak.storage.client.ClientLookupProvider;
import java.util.List;
import java.util.Set;
/**
* Provider of the client records.
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface ClientProvider extends ClientLookupProvider, Provider {
/**
* Returns the clients of the given realm.
* @param realm Realm.
* @param firstResult First result to return. Ignored if negative or {@code null}.
* @param maxResults Maximim number of results to return. Ignored if negative or {@code null}.
* @return List of the clients. Never returns {@code null}.
*/
List<ClientModel> getClients(RealmModel realm, Integer firstResult, Integer maxResults);
List<ClientModel> getClients(RealmModel realm);
/**
* Returns all the clients of the given realm.
* Effectively the same as the call {@code getClients(realm, null, null)}.
* @param realm Realm.
* @return List of the clients. Never returns {@code null}.
*/
default List<ClientModel> getClients(RealmModel realm) {
return this.getClients(realm, null, null);
}
ClientModel addClient(RealmModel realm, String clientId);
/**
* Adds a client with given {@code clientId} to the given realm.
* The internal ID of the client will be created automatically.
* @param realm Realm owning this client.
* @param clientId String that identifies the client to the external parties.
* Maps to {@code client_id} in OIDC or {@code entityID} in SAML.
* @return Model of the created client.
*/
default ClientModel addClient(RealmModel realm, String clientId) {
return addClient(realm, null, clientId);
}
/**
* Adds a client with given internal ID and {@code clientId} to the given realm.
* @param realm Realm owning this client.
* @param id Internal ID of the client or {@code null} if one is to be created by the underlying store
* @param clientId String that identifies the client to the external parties.
* Maps to {@code client_id} in OIDC or {@code entityID} in SAML.
* @return Model of the created client.
* @throws IllegalArgumentException If {@code id} does not conform
* the format understood by the underlying store.
*/
ClientModel addClient(RealmModel realm, String id, String clientId);
RoleModel addClientRole(RealmModel realm, ClientModel client, String name);
RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name);
RoleModel getClientRole(RealmModel realm, ClientModel client, String name);
Set<RoleModel> getClientRoles(RealmModel realm, ClientModel client);
/**
* Returns number of clients in the given realm
* @param realm Realm.
* @return Number of the clients in the given realm.
*/
long getClientsCount(RealmModel realm);
/**
* Returns a list of clients that are expected to always show up in account console.
* @param realm Realm owning the clients.
* @return List of the clients. Never returns {@code null}.
*/
List<ClientModel> getAlwaysDisplayInConsoleClients(RealmModel realm);
boolean removeClient(String id, RealmModel realm);
/**
* Removes given client from the given realm.
* @param id Internal ID of the client
* @param realm Realm.
* @return {@code true} if the client existed and has been removed, {@code false} otherwise.
* @deprecated Use {@link #removeClient(RealmModel, String)} instead.
*/
default boolean removeClient(String id, RealmModel realm) { return this.removeClient(realm, id); }
/**
* Removes given client from the given realm.
* @param realm Realm.
* @param id Internal ID of the client
* @return {@code true} if the client existed and has been removed, {@code false} otherwise.
*/
boolean removeClient(RealmModel realm, String id);
/**
* Removes all clients from the given realm.
* @param realm Realm.
*/
void removeClients(RealmModel realm);
}

View file

@ -106,6 +106,15 @@ public interface KeycloakSession {
*/
RealmProvider realms();
/**
* Returns a managed provider instance. Will start a provider transaction. This transaction is managed by the KeycloakSession
* transaction.
*
* @return
* @throws IllegalStateException if transaction is not active
*/
ClientProvider clients();
/**
* Returns a managed provider instance. Will start a provider transaction. This transaction is managed by the KeycloakSession
* transaction.

View file

@ -27,7 +27,7 @@ import java.util.Set;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface RealmProvider extends Provider, ClientProvider {
public interface RealmProvider extends Provider /* TODO: Remove in future version */, ClientProvider /* up to here */ {
// Note: The reason there are so many query methods here is for layering a cache on top of an persistent KeycloakSession
MigrationModel getMigrationModel();
@ -42,7 +42,10 @@ public interface RealmProvider extends Provider, ClientProvider {
Long getGroupsCount(RealmModel realm, Boolean onlyTopGroups);
Long getClientsCount(RealmModel realm);
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
long getClientsCount(RealmModel realm);
Long getGroupsCountByNameContaining(RealmModel realm, String search);
@ -101,7 +104,6 @@ public interface RealmProvider extends Provider, ClientProvider {
List<RealmModel> getRealms();
List<RealmModel> getRealmsWithProviderType(Class<?> type);
boolean removeRealm(String id);
void close();
ClientInitialAccessModel createClientInitialAccessModel(RealmModel realm, int expiration, int count);
ClientInitialAccessModel getClientInitialAccessModel(RealmModel realm, String id);
@ -110,4 +112,94 @@ public interface RealmProvider extends Provider, ClientProvider {
void removeExpiredClientInitialAccess();
void decreaseRemainingCount(RealmModel realm, ClientInitialAccessModel clientInitialAccess); // Separate provider method to ensure we decrease remainingCount atomically instead of doing classic update
/**
* TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */
public Set<RoleModel> getClientRoles(RealmModel realm, ClientModel client);
/**
* TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */
public RoleModel getClientRole(RealmModel realm, ClientModel client, String name);
/**
* TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */
public RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name);
/**
* TODO: To be @deprecated Use the corresponding method from {@link ??RoleProvider}. */
public RoleModel addClientRole(RealmModel realm, ClientModel client, String name);
// The methods below are going to be removed in future version of Keycloak
// Sadly, we have to copy-paste the declarations from the respective interfaces
// including the "default" body to be able to add a note on deprecation
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
public ClientModel addClient(RealmModel realm, String id, String clientId);
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
default ClientModel addClient(RealmModel realm, String clientId) {
return addClient(realm, null, clientId);
}
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
default List<ClientModel> getClients(RealmModel realm) {
return this.getClients(realm, null, null);
}
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
public List<ClientModel> getClients(RealmModel realm, Integer firstResult, Integer maxResults);
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
default List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
return searchClientsByClientId(realm, clientId, firstResult, maxResults);
}
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
default ClientModel getClientByClientId(String clientId, RealmModel realm) { return getClientByClientId(realm, clientId); }
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
default ClientModel getClientById(String id, RealmModel realm) { return getClientById(realm, id); }
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
public List<ClientModel> searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults);
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
public ClientModel getClientByClientId(RealmModel realm, String clientId);
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
public ClientModel getClientById(RealmModel realm, String id);
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
public boolean removeClient(RealmModel realm, String id);
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
default boolean removeClient(String id, RealmModel realm) { return this.removeClient(realm, id); }
/**
* @deprecated Use the corresponding method from {@link ClientProvider}. */
@Override
public List<ClientModel> getAlwaysDisplayInConsoleClients(RealmModel realm);
}

View file

@ -32,9 +32,7 @@ public interface ScopeContainerModel {
return getScopeMappingsStream().collect(Collectors.toSet());
}
default Stream<RoleModel> getScopeMappingsStream() {
return getScopeMappings().stream();
};
Stream<RoleModel> getScopeMappingsStream();
/**
* From the scope mappings returned by {@link #getScopeMappings()} returns only those

View file

@ -28,7 +28,65 @@ import java.util.List;
* @version $Revision: 1 $
*/
public interface ClientLookupProvider {
ClientModel getClientById(String id, RealmModel realm);
ClientModel getClientByClientId(String clientId, RealmModel realm);
List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm);
/**
* Exact search for a client by its internal ID.
* @param realm Realm to limit the search.
* @param id Internal ID
* @return Model of the client, or {@code null} if no client is found.
*/
ClientModel getClientById(RealmModel realm, String id);
/**
* Exact search for a client by its internal ID.
* @param realm Realm to limit the search.
* @param id Internal ID
* @return Model of the client, or {@code null} if no client is found.
* @deprecated Use {@link #getClientById(org.keycloak.models.RealmModel, java.lang.String)} instead.
*/
default ClientModel getClientById(String id, RealmModel realm) { return getClientById(realm, id); }
/**
* Exact search for a client by its public client identifier.
* @param realm Realm to limit the search for clients.
* @param clientId String that identifies the client to the external parties.
* Maps to {@code client_id} in OIDC or {@code entityID} in SAML.
* @return Model of the client, or {@code null} if no client is found.
*/
ClientModel getClientByClientId(RealmModel realm, String clientId);
/**
* Exact search for a client by its public client identifier.
* @param realm Realm to limit the search.
* @param clientId String that identifies the client to the external parties.
* Maps to {@code client_id} in OIDC or {@code entityID} in SAML.
* @return Model of the client, or {@code null} if no client is found.
* @deprecated Use {@link #getClientByClientId(org.keycloak.models.RealmModel, java.lang.String)} instead.
*/
default ClientModel getClientByClientId(String clientId, RealmModel realm) { return getClientByClientId(realm, clientId); }
/**
* Case-insensitive search for clients that contain the given string in their public client identifier.
* @param realm Realm to limit the search for clients.
* @param clientId Searched substring of the public client
* identifier ({@code client_id} in OIDC or {@code entityID} in SAML.)
* @param firstResult First result to return. Ignored if negative or {@code null}.
* @param maxResults Maximim number of results to return. Ignored if negative or {@code null}.
* @return Model of the client, or {@code null} if no client is found.
*/
List<ClientModel> searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults);
/**
* Case-insensitive search for clients that contain the given string in their public client identifier.
* @param realm Realm to limit the search for clients.
* @param clientId Searched substring of the public client
* identifier ({@code client_id} in OIDC or {@code entityID} in SAML.)
* @param firstResult First result to return. Ignored if negative or {@code null}.
* @param maxResults Maximim number of results to return. Ignored if negative or {@code null}.
* @return Models of the matching clients. Never returns {@code null}.
* @deprecated Use {@link #searchClientsByClientId(org.keycloak.models.RealmModel, java.lang.String, java.lang.Integer, java.lang.Integer)} instead.
*/
default List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
return searchClientsByClientId(realm, clientId, firstResult, maxResults);
}
}

View file

@ -101,7 +101,7 @@ public class ClientIdAndSecretAuthenticator extends AbstractClientAuthenticator
context.getEvent().client(client_id);
ClientModel client = context.getRealm().getClientByClientId(client_id);
ClientModel client = context.getSession().clients().getClientByClientId(context.getRealm(), client_id);
if (client == null) {
context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
return;

View file

@ -55,7 +55,7 @@ public class LoginStatusIframeEndpoint {
try {
UriInfo uriInfo = session.getContext().getUri();
RealmModel realm = session.getContext().getRealm();
ClientModel client = session.realms().getClientByClientId(clientId, realm);
ClientModel client = session.clients().getClientByClientId(realm, clientId);
if (client != null && client.isEnabled()) {
Set<String> validWebOrigins = WebOriginsUtils.resolveValidWebOrigins(session, client);
validWebOrigins.add(UriUtils.getOrigin(uriInfo.getRequestUri()));

View file

@ -66,6 +66,7 @@ public class DefaultKeycloakSession implements KeycloakSession {
private final DefaultKeycloakTransactionManager transactionManager;
private final Map<String, Object> attributes = new HashMap<>();
private RealmProvider model;
private ClientProvider clientProvider;
private UserStorageManager userStorageManager;
private ClientStorageManager clientStorageManager;
private UserCredentialStoreManager userCredentialStorageManager;
@ -99,6 +100,16 @@ public class DefaultKeycloakSession implements KeycloakSession {
}
}
private ClientProvider getClientProvider() {
// TODO: Extract ClientProvider from CacheRealmProvider and use that instead
ClientProvider cache = getProvider(CacheRealmProvider.class);
if (cache != null) {
return cache;
} else {
return clientStorageManager();
}
}
@Override
public UserCache userCache() {
return getProvider(UserCache.class);
@ -162,7 +173,7 @@ public class DefaultKeycloakSession implements KeycloakSession {
@Override
public ClientProvider clientLocalStorage() {
return realmLocalStorage();
return getProvider(ClientProvider.class);
}
@Override
@ -275,6 +286,14 @@ public class DefaultKeycloakSession implements KeycloakSession {
return model;
}
@Override
public ClientProvider clients() {
if (clientProvider == null) {
clientProvider = getClientProvider();
}
return clientProvider;
}
@Override
public UserSessionProvider sessions() {

View file

@ -66,7 +66,7 @@ public abstract class AbstractClientRegistrationProvider implements ClientRegist
try {
RealmModel realm = session.getContext().getRealm();
ClientModel clientModel = new ClientManager(new RealmManager(session)).createClient(session, realm, client, true);
ClientModel clientModel = ClientManager.createClient(session, realm, client, true);
if (clientModel.isServiceAccountsEnabled()) {
new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);

View file

@ -177,7 +177,7 @@ public class RealmManager {
}
protected void setupAdminConsoleLocaleMapper(RealmModel realm) {
ClientModel adminConsole = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
ClientModel adminConsole = session.clients().getClientByClientId(realm, Constants.ADMIN_CONSOLE_CLIENT_ID);
ProtocolMapperModel localeMapper = adminConsole.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, OIDCLoginProtocolFactory.LOCALE);
if (localeMapper == null) {
@ -251,7 +251,7 @@ public class RealmManager {
boolean removed = model.removeRealm(realm.getId());
if (removed) {
if (masterAdminClient != null) {
new ClientManager(this).removeClient(getKeycloakAdminstrationRealm(), masterAdminClient);
session.clients().removeClient(getKeycloakAdminstrationRealm(), masterAdminClient.getId());
}
UserSessionProvider sessions = session.sessions();

View file

@ -395,7 +395,7 @@ public class LoginActionsService {
throws UriBuilderException, IllegalArgumentException {
AuthenticationSessionModel authSession;
ClientModel client = session.realms().getClientByClientId(clientID, realm);
ClientModel client = session.clients().getClientByClientId(realm, clientID);
String redirectUri;
if (client == null) {

View file

@ -194,19 +194,19 @@ public class RoleByIdResource extends RoleResource {
* Get client-level roles for the client that are in the role's composite
*
* @param id
* @param client
* @param clientUuid
* @return
*/
@Path("{role-id}/composites/clients/{client}")
@Path("{role-id}/composites/clients/{clientUuid}")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Set<RoleRepresentation> getClientRoleComposites(final @PathParam("role-id") String id,
final @PathParam("client") String client) {
final @PathParam("clientUuid") String clientUuid) {
RoleModel role = getRoleModel(id);
auth.roles().requireView(role);
ClientModel clientModel = realm.getClientById(client);
ClientModel clientModel = realm.getClientById(clientUuid);
if (clientModel == null) {
throw new NotFoundException("Could not find client");
}

View file

@ -289,25 +289,25 @@ public class RoleContainerResource extends RoleResource {
}
/**
* An app-level roles for the specified app for the role's composite
* Get client-level roles for the client that are in the role's composite
*
* @param roleName role's name (not id!)
* @param client
* @param clientUuid
* @return
*/
@Path("{role-name}/composites/clients/{client}")
@Path("{role-name}/composites/clients/{clientUuid}")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Set<RoleRepresentation> getClientRoleComposites(final @PathParam("role-name") String roleName,
final @PathParam("client") String client) {
final @PathParam("clientUuid") String clientUuid) {
auth.roles().requireView(roleContainer);
RoleModel role = roleContainer.getRole(roleName);
if (role == null) {
throw new NotFoundException("Could not find role");
}
ClientModel clientModel = realm.getClientById(client);
if (client == null) {
ClientModel clientModel = realm.getClientById(clientUuid);
if (clientModel == null) {
throw new NotFoundException("Could not find client");
}

View file

@ -357,13 +357,13 @@ public class UserResource {
*
* @return
*/
@Path("offline-sessions/{clientId}")
@Path("offline-sessions/{clientUuid}")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<UserSessionRepresentation> getOfflineSessions(final @PathParam("clientId") String clientId) {
public List<UserSessionRepresentation> getOfflineSessions(final @PathParam("clientUuid") String clientUuid) {
auth.users().requireView(user);
ClientModel client = realm.getClientById(clientId);
ClientModel client = realm.getClientById(clientUuid);
if (client == null) {
throw new NotFoundException("Client not found");
}
@ -373,7 +373,7 @@ public class UserResource {
UserSessionRepresentation rep = ModelToRepresentation.toRepresentation(session);
// Update lastSessionRefresh with the timestamp from clientSession
AuthenticatedClientSessionModel clientSession = session.getAuthenticatedClientSessionByClient(clientId);
AuthenticatedClientSessionModel clientSession = session.getAuthenticatedClientSessionByClient(clientUuid);
// Skip if userSession is not for this client
if (clientSession == null) {

View file

@ -24,16 +24,13 @@ import org.keycloak.models.ClientProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.storage.client.ClientLookupProvider;
import org.keycloak.storage.client.ClientStorageProvider;
import org.keycloak.storage.client.ClientStorageProviderFactory;
import org.keycloak.storage.client.ClientStorageProviderModel;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -126,38 +123,38 @@ public class ClientStorageManager implements ClientProvider {
}
@Override
public ClientModel getClientById(String id, RealmModel realm) {
public ClientModel getClientById(RealmModel realm, String id) {
StorageId storageId = new StorageId(id);
if (storageId.getProviderId() == null) {
return session.clientLocalStorage().getClientById(id, realm);
return session.clientLocalStorage().getClientById(realm, id);
}
ClientLookupProvider provider = (ClientLookupProvider)getStorageProvider(session, realm, storageId.getProviderId());
if (provider == null) return null;
if (!isStorageProviderEnabled(realm, storageId.getProviderId())) return null;
return provider.getClientById(id, realm);
return provider.getClientById(realm, id);
}
@Override
public ClientModel getClientByClientId(String clientId, RealmModel realm) {
ClientModel client = session.clientLocalStorage().getClientByClientId(clientId, realm);
public ClientModel getClientByClientId(RealmModel realm, String clientId) {
ClientModel client = session.clientLocalStorage().getClientByClientId(realm, clientId);
if (client != null) {
return client;
}
for (ClientLookupProvider provider : getEnabledStorageProviders(session, realm, ClientLookupProvider.class)) {
client = provider.getClientByClientId(clientId, realm);
client = provider.getClientByClientId(realm, clientId);
if (client != null) return client;
}
return null;
}
@Override
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
List<ClientModel> clients = session.clientLocalStorage().searchClientsByClientId(clientId, firstResult, maxResults, realm);
public List<ClientModel> searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) {
List<ClientModel> clients = session.clientLocalStorage().searchClientsByClientId(realm, clientId, firstResult, maxResults);
if (clients != null) {
return clients;
}
for (ClientLookupProvider provider : getEnabledStorageProviders(session, realm, ClientLookupProvider.class)) {
clients = provider.searchClientsByClientId(clientId, firstResult, maxResults, realm);
clients = provider.searchClientsByClientId(realm, clientId, firstResult, maxResults);
if (clients != null) return clients;
}
return null;
@ -173,9 +170,6 @@ public class ClientStorageManager implements ClientProvider {
return session.clientLocalStorage().addClient(realm, id, clientId);
}
@Override
public List<ClientModel> getClients(RealmModel realm, Integer firstResult, Integer maxResults) {
return session.clientLocalStorage().getClients(realm, firstResult, maxResults);
@ -187,37 +181,8 @@ public class ClientStorageManager implements ClientProvider {
}
@Override
public RoleModel addClientRole(RealmModel realm, ClientModel client, String name) {
if (!StorageId.isLocalStorage(client.getId())) {
throw new RuntimeException("Federated clients do not support this operation");
}
return session.clientLocalStorage().addClientRole(realm, client, name);
}
@Override
public RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name) {
if (!StorageId.isLocalStorage(client.getId())) {
throw new RuntimeException("Federated clients do not support this operation");
}
return session.clientLocalStorage().addClientRole(realm, client, id, name);
}
@Override
public RoleModel getClientRole(RealmModel realm, ClientModel client, String name) {
if (!StorageId.isLocalStorage(client.getId())) {
//throw new RuntimeException("Federated clients do not support this operation");
return null;
}
return session.clientLocalStorage().getClientRole(realm, client, name);
}
@Override
public Set<RoleModel> getClientRoles(RealmModel realm, ClientModel client) {
if (!StorageId.isLocalStorage(client.getId())) {
//throw new RuntimeException("Federated clients do not support this operation");
return Collections.EMPTY_SET;
}
return session.clientLocalStorage().getClientRoles(realm, client);
public long getClientsCount(RealmModel realm) {
return session.clientLocalStorage().getClientsCount(realm);
}
@Override
@ -225,17 +190,22 @@ public class ClientStorageManager implements ClientProvider {
return session.clientLocalStorage().getAlwaysDisplayInConsoleClients(realm);
}
@Override
public void removeClients(RealmModel realm) {
session.clientLocalStorage().removeClients(realm);
}
@Override
public void close() {
}
@Override
public boolean removeClient(String id, RealmModel realm) {
public boolean removeClient(RealmModel realm, String id) {
if (!StorageId.isLocalStorage(id)) {
throw new RuntimeException("Federated clients do not support this operation");
}
return session.clientLocalStorage().removeClient(id, realm);
return session.clientLocalStorage().removeClient(realm, id);
}

View file

@ -46,15 +46,15 @@ public class OpenshiftClientStorageProvider implements ClientStorageProvider {
}
@Override
public ClientModel getClientById(String id, RealmModel realm) {
public ClientModel getClientById(RealmModel realm, String id) {
StorageId storageId = new StorageId(id);
if (!storageId.getProviderId().equals(providerModel.getId())) return null;
String clientId = storageId.getExternalId();
return getClientByClientId(clientId, realm);
return getClientByClientId(realm, clientId);
}
@Override
public ClientModel getClientByClientId(String clientId, RealmModel realm) {
public ClientModel getClientByClientId(RealmModel realm, String clientId) {
Matcher matcher = OpenshiftClientStorageProviderFactory.SERVICE_ACCOUNT_PATTERN.matcher(clientId);
IResource resource = null;
@ -76,9 +76,9 @@ public class OpenshiftClientStorageProvider implements ClientStorageProvider {
}
@Override
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
public List<ClientModel> searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) {
// TODO not sure about this, but I don't see this implementation using the search now
return Collections.singletonList(getClientByClientId(clientId, realm));
return Collections.singletonList(getClientByClientId(realm, clientId));
}
@Override

View file

@ -345,8 +345,8 @@ public final class OpenshiftSAClientAdapter extends AbstractReadOnlyClientStorag
}
@Override
public Set<RoleModel> getScopeMappings() {
return Collections.emptySet();
public Stream<RoleModel> getScopeMappingsStream() {
return Stream.empty();
}
@Override
@ -464,8 +464,8 @@ public final class OpenshiftSAClientAdapter extends AbstractReadOnlyClientStorag
}
@Override
public Set<RoleModel> getScopeMappings() {
return Collections.emptySet();
public Stream<RoleModel> getScopeMappingsStream() {
return Stream.empty();
}
@Override

View file

@ -38,6 +38,7 @@ import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -59,7 +60,7 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl
}
@Override
public ClientModel getClientById(String id, RealmModel realm) {
public ClientModel getClientById(RealmModel realm, String id) {
StorageId storageId = new StorageId(id);
final String clientId = storageId.getExternalId();
if (this.clientId.equals(clientId)) return new ClientAdapter(realm);
@ -67,7 +68,7 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl
}
@Override
public ClientModel getClientByClientId(String clientId, RealmModel realm) {
public ClientModel getClientByClientId(RealmModel realm, String clientId) {
if (this.clientId.equals(clientId)) return new ClientAdapter(realm);
return null;
}
@ -78,7 +79,7 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl
}
@Override
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
public List<ClientModel> searchClientsByClientId(RealmModel realm, String clientId, Integer firstResult, Integer maxResults) {
if (clientId != null && this.clientId.toLowerCase().contains(clientId.toLowerCase())) {
return Collections.singletonList(new ClientAdapter(realm));
}
@ -274,11 +275,8 @@ public class HardcodedClientStorageProvider implements ClientStorageProvider, Cl
}
@Override
public Set<RoleModel> getScopeMappings() {
RoleModel offlineAccess = realm.getRole("offline_access");
Set<RoleModel> set = new HashSet<>();
set.add(offlineAccess);
return set;
public Stream<RoleModel> getScopeMappingsStream() {
return Stream.of(realm.getRole("offline_access"));
}
@Override

View file

@ -102,7 +102,7 @@ public class UserStorageConsentTest extends AbstractServletsAdapterTest {
public static void setupConsent(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName("demo");
ClientModel product = session.realms().getClientByClientId("product-portal", realm);
ClientModel product = session.clients().getClientByClientId(realm, "product-portal");
product.setConsentRequired(true);
ClientScopeModel clientScope = realm.addClientScope("clientScope");
clientScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

View file

@ -97,7 +97,7 @@ public class ConsentsTest extends AbstractKeycloakTest {
protected List<ClientRepresentation> createProviderClients() {
ClientRepresentation client = new ClientRepresentation();
client.setId(CLIENT_ID);
client.setClientId(CLIENT_ID);
client.setName(CLIENT_ID);
client.setSecret(CLIENT_SECRET);
client.setEnabled(true);

View file

@ -1260,7 +1260,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
private static void setupTokenExchange(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName("master");
ClientModel client = session.realms().getClientByClientId("kcinit", realm);
ClientModel client = session.clients().getClientByClientId(realm, "kcinit");
if (client != null) {
return;
}

View file

@ -85,6 +85,8 @@ import static org.keycloak.services.resources.admin.AdminAuth.Resource.CLIENT;
import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot;
import org.keycloak.testsuite.utils.tls.TLSUtils;
import org.jgroups.util.UUID;
import org.keycloak.models.utils.KeycloakModelUtils;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
@ -712,7 +714,7 @@ public class PermissionsTest extends AbstractKeycloakTest {
invoke(new Invocation() {
public void invoke(RealmResource realm) {
realm.clients().get("nosuch").roles().list();
realm.clients().get(UUID.randomUUID().toString()).roles().list();
}
}, Resource.CLIENT, false, true);
invoke(new Invocation() {
@ -1070,7 +1072,7 @@ public class PermissionsTest extends AbstractKeycloakTest {
}, Resource.REALM, false);
invoke(new Invocation() {
public void invoke(RealmResource realm) {
realm.roles().get("sample-role").getClientRoleComposites("nosuch");
realm.roles().get("sample-role").getClientRoleComposites(KeycloakModelUtils.generateId());
}
}, Resource.REALM, false);
adminClient.realms().realm(REALM_NAME).roles().deleteRole("sample-role");
@ -1297,7 +1299,7 @@ public class PermissionsTest extends AbstractKeycloakTest {
}, Resource.REALM, false, true);
invoke(new Invocation() {
public void invoke(RealmResource realm) {
realm.rolesById().getClientRoleComposites(role.getId(), "nosuch");
realm.rolesById().getClientRoleComposites(role.getId(), KeycloakModelUtils.generateId());
}
}, Resource.REALM, false, true);
@ -1457,7 +1459,7 @@ public class PermissionsTest extends AbstractKeycloakTest {
}, Resource.USER, false);
invoke(new Invocation() {
public void invoke(RealmResource realm) {
realm.users().get(user.getId()).getOfflineSessions("nosuch");
realm.users().get(user.getId()).getOfflineSessions(KeycloakModelUtils.generateId());
}
}, Resource.USER, false);
invoke(new Invocation() {

View file

@ -69,7 +69,7 @@ public class PolicyEvaluationCompositeRoleTest extends AbstractAuthzTest {
session.getContext().setRealm(realm);
ClientModel client = session.realms().addClient(realm, "myclient");
ClientModel client = session.clients().addClient(realm, "myclient");
RoleModel role1 = client.addRole("client-role1");

View file

@ -133,7 +133,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckDateAndTime(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
TimePolicyRepresentation policyRepresentation = new TimePolicyRepresentation();
@ -168,7 +168,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckUserInGroup(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -327,7 +327,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckUserInRole(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -374,7 +374,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckUserInClientRole(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -421,7 +421,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckGroupInRole(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -468,7 +468,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckUserRealmRoles(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -500,7 +500,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckUserClientRoles(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -532,7 +532,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckUserGroups(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -570,7 +570,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
session.getContext().setRealm(realm);
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -602,7 +602,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckResourceAttributes(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -639,7 +639,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCheckReadOnlyInstances(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
@ -685,7 +685,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
public static void testCachedDecisionsWithNegativePolicies(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());

View file

@ -8,6 +8,7 @@ import org.keycloak.broker.oidc.mappers.AbstractJsonUserAttributeMapper;
import org.keycloak.models.IdentityProviderMapperModel;
import org.keycloak.models.IdentityProviderMapperSyncMode;
import org.keycloak.protocol.oidc.mappers.HardcodedClaim;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.IdentityProviderMapperRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
@ -126,7 +127,8 @@ public class JsonUserAttributeMapperTest extends AbstractIdentityProviderMapperT
private void updateClaimSentToIDP(String claim, String updatedValue) {
ProtocolMapperRepresentation claimMapper = null;
ProtocolMappersResource protocolMappers = adminClient.realm(bc.providerRealmName()).clients().get(BrokerTestConstants.CLIENT_ID).getProtocolMappers();
final ClientRepresentation brokerClient = adminClient.realm(bc.providerRealmName()).clients().findByClientId(BrokerTestConstants.CLIENT_ID).get(0);
ProtocolMappersResource protocolMappers = adminClient.realm(bc.providerRealmName()).clients().get(brokerClient.getId()).getProtocolMappers();
for (ProtocolMapperRepresentation representation : protocolMappers.getMappers()) {
if (representation.getProtocolMapper().equals(HardcodedClaim.PROVIDER_ID)) {
claimMapper = representation;
@ -134,7 +136,7 @@ public class JsonUserAttributeMapperTest extends AbstractIdentityProviderMapperT
}
assertThat(claimMapper, notNullValue());
claimMapper.getConfig().put(HardcodedClaim.CLAIM_VALUE, "{\"" + claim + "\": \"" + updatedValue + "\"}");
adminClient.realm(bc.providerRealmName()).clients().get(BrokerTestConstants.CLIENT_ID).getProtocolMappers().update(claimMapper.getId(), claimMapper);
adminClient.realm(bc.providerRealmName()).clients().get(brokerClient.getId()).getProtocolMappers().update(claimMapper.getId(), claimMapper);
}
private void assertUserAttribute(String value, UserRepresentation userRep) {

View file

@ -57,7 +57,6 @@ public class KcOidcBrokerConfiguration implements BrokerConfiguration {
@Override
public List<ClientRepresentation> createProviderClients() {
ClientRepresentation client = new ClientRepresentation();
client.setId(CLIENT_ID);
client.setClientId(getIDPClientIdInProviderRealm());
client.setName(CLIENT_ID);
client.setSecret(CLIENT_SECRET);
@ -155,7 +154,6 @@ public class KcOidcBrokerConfiguration implements BrokerConfiguration {
@Override
public List<ClientRepresentation> createConsumerClients() {
ClientRepresentation client = new ClientRepresentation();
client.setId("broker-app");
client.setClientId("broker-app");
client.setName("broker-app");
client.setSecret("broker-app-secret");

View file

@ -185,7 +185,6 @@ public class KcSamlBrokerConfiguration implements BrokerConfiguration {
.attribute(SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE, getConsumerRoot() + "/sales-post/saml")
.build(),
ClientBuilder.create()
.id("broker-app")
.clientId("broker-app")
.name("broker-app")
.secret("broker-app-secret")

View file

@ -209,7 +209,7 @@ public class SocialLoginTest extends AbstractKeycloakTest {
public static void setupClientExchangePermissions(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName(REALM);
ClientModel client = session.realms().getClientByClientId(EXCHANGE_CLIENT, realm);
ClientModel client = session.clients().getClientByClientId(realm, EXCHANGE_CLIENT);
// lazy init
if (client != null) return;
client = realm.addClient(EXCHANGE_CLIENT);

View file

@ -102,7 +102,7 @@ public class KcinitTest extends AbstractTestRealmKeycloakTest {
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealmByName("test");
ClientModel client = session.realms().getClientByClientId("kcinit", realm);
ClientModel client = session.clients().getClientByClientId(realm, "kcinit");
if (client != null) {
return;
}

View file

@ -84,7 +84,7 @@ public class ChallengeFlowTest extends AbstractTestRealmKeycloakTest {
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealmByName("test");
ClientModel client = session.realms().getClientByClientId("test-app-flow", realm);
ClientModel client = session.clients().getClientByClientId(realm, "test-app-flow");
if (client != null) {
return;
}

View file

@ -99,12 +99,12 @@ public class FlowOverrideTest extends AbstractTestRealmKeycloakTest {
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealmByName("test");
ClientModel client = session.realms().getClientByClientId("test-app-flow", realm);
ClientModel client = session.clients().getClientByClientId(realm, "test-app-flow");
if (client != null) {
return;
}
client = session.realms().getClientByClientId("test-app", realm);
client = session.clients().getClientByClientId(realm, "test-app");
client.setDirectAccessGrantsEnabled(true);
// Parent flow

View file

@ -99,7 +99,7 @@ public class CacheTest extends AbstractTestRealmKeycloakTest {
realm = session.realms().getRealmByName("test");
Assert.assertEquals(200, realm.getAccessCodeLifespanLogin());
testApp = session.realms().getClientById(appId, realm);
testApp = session.clients().getClientById(realm, appId);
Assert.assertFalse(testApp.isEnabled());
}

View file

@ -141,7 +141,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
RoleModel role = currentSession.realms().getRoleById(roleId, realm);
from.removeRole(role);
currentSession.realms().removeClient(from.getId(), realm);
currentSession.clients().removeClient(realm, from.getId());
});
@ -155,7 +155,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
// used to throw an NPE
assertThat("Scope Mappings must be 0", scopeMappings.size(), is(0));
currentSession.realms().removeClient(scoped.getId(), realm);
currentSession.clients().removeClient(realm, scoped.getId());
});
}
@ -191,8 +191,8 @@ public class ClientModelTest extends AbstractKeycloakTest {
// used to throw an NPE
assertThat("Scope Mappings is not 0", scopeMappings.size(), is(0));
currentSession.realms().removeClient(scoped.getId(), realm);
currentSession.realms().removeClient(from.getId(), realm);
currentSession.clients().removeClient(realm, scoped.getId());
currentSession.clients().removeClient(realm, from.getId());
});
}
@ -227,7 +227,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
Set<RoleModel> scopeMappings = scoped.getScopeMappings();
// used to throw an NPE
assertThat("Scope Mappings is not 0", scopeMappings.size(), is(0));
currentSession.realms().removeClient(scoped.getId(), realm);
currentSession.clients().removeClient(realm, scoped.getId());
});
}
@ -252,7 +252,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
// this hit the circular cache and failed with a stack overflow
ClientModel scoped1 = realm.getClientByClientId("scoped1");
currentSession.realms().removeClient(scoped1.getId(), realm);
currentSession.clients().removeClient(realm, scoped1.getId());
});
}
@ -270,7 +270,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
client.unregisterNode("node1");
client.unregisterNode("10.20.30.40");
currentSession.realms().removeClient(client.getId(), realm);
currentSession.clients().removeClient(realm, client.getId());
});
}
@ -296,8 +296,8 @@ public class ClientModelTest extends AbstractKeycloakTest {
client.unregisterNode("node1");
client.unregisterNode("10.20.30.40");
currentSession.realms().removeClient(client.getId(), realm);
currentSession.realms().removeClient(copyClient.getId(), realm);
currentSession.clients().removeClient(realm, client.getId());
currentSession.clients().removeClient(realm, copyClient.getId());
currentSession.realms().removeRealm(realm.getId());
});
}
@ -305,21 +305,22 @@ public class ClientModelTest extends AbstractKeycloakTest {
@Test
@ModelTest
public void testAddApplicationWithId(KeycloakSession session) {
final String id = KeycloakModelUtils.generateId();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionAppWithId1) -> {
currentSession = sessionAppWithId1;
RealmModel realm = currentSession.realms().getRealmByName(realmName);
client = realm.addClient("app-123", "application2");
client = realm.addClient(id, "application2");
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionAppWithId2) -> {
currentSession = sessionAppWithId2;
RealmModel realm = currentSession.realms().getRealmByName(realmName);
client = currentSession.realms().getClientById("app-123", realm);
client = currentSession.clients().getClientById(realm, id);
assertThat("Client 'app-123' is NULL!!", client, notNullValue());
currentSession.realms().removeClient(client.getId(), realm);
currentSession.clients().removeClient(realm, client.getId());
});
}
@ -407,7 +408,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(false));
assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true));
currentSession.realms().removeClient(client.getId(), realm);
currentSession.clients().removeClient(realm, client.getId());
client.removeClientScope(scope3);
realm.removeClientScope(scope1Atomic.get().getId());
realm.removeClientScope(scope2Atomic.get().getId());
@ -444,7 +445,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
// Expected
}
currentSession.realms().removeClient(client.getId(), realm);
currentSession.clients().removeClient(realm, client.getId());
realm.removeClientScope(scope1Atomic.get().getId());
assertThat("Error with removing Client from realm.", realm.getClientById(client.getId()), nullValue());
@ -521,7 +522,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(true));
assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true));
currentSession.realms().removeClient(client.getId(), realm);
currentSession.clients().removeClient(realm, client.getId());
// Remove some realm default client scopes
realm.removeDefaultClientScope(scope1);
realm.removeDefaultClientScope(scope2);
@ -549,7 +550,7 @@ public class ClientModelTest extends AbstractKeycloakTest {
assertThat("Client Scope contains 'scope2':", clientScopes2.containsKey("scope2"), is(false));
assertThat("Client Scope contains 'scope3':", clientScopes2.containsKey("scope3"), is(true));
currentSession.realms().removeClient(client.getId(), realm);
currentSession.clients().removeClient(realm, client.getId());
realm.removeClientScope(scope1Atomic.get().getId());
realm.removeClientScope(scope2Atomic.get().getId());

View file

@ -21,10 +21,10 @@ import org.jboss.logging.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.UserManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils;
@ -69,7 +69,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest {
realm = sessionSetup.realms().createRealm("original");
client[0] = sessionSetup.realms().addClient(realm, "client");
client[0] = sessionSetup.clients().addClient(realm, "client");
client[0].setSecret("old");
});
@ -96,7 +96,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest {
// Read client
RealmModel realm1 = currentSession.realms().getRealmByName("original");
ClientModel client1 = currentSession.realms().getClientByClientId("client", realm1);
ClientModel client1 = currentSession.clients().getClientByClientId(realm1, "client");
logger.info("transaction1: Read client finished");
readLatch.countDown();
@ -107,7 +107,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest {
logger.info("transaction1: Going to read client again");
client1 = currentSession.realms().getClientByClientId("client", realm1);
client1 = currentSession.clients().getClientByClientId(realm1, "client");
logger.info("transaction1: secret: " + client1.getSecret());
} catch (Exception e) {
@ -136,7 +136,7 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest {
logger.info("transaction2: Going to update client secret");
RealmModel realm12 = currentSession.realms().getRealmByName("original");
ClientModel client12 = currentSession.realms().getClientByClientId("client", realm12);
ClientModel client12 = currentSession.clients().getClientByClientId(realm12, "client");
client12.setSecret("new");
} catch (Exception e) {
exceptionHolder.set(e);
@ -168,8 +168,8 @@ public class ConcurrentTransactionsTest extends AbstractTestRealmKeycloakTest {
RealmModel realm = session2.realms().getRealmByName("original");
String clientDBId = clientDBIdAtomic.get();
ClientModel clientFromCache = session2.realms().getClientById(clientDBId, realm);
ClientModel clientFromDB = session2.getProvider(RealmProvider.class).getClientById(clientDBId, realm);
ClientModel clientFromCache = session2.clients().getClientById(realm, clientDBId);
ClientModel clientFromDB = session2.getProvider(ClientProvider.class).getClientById(realm, clientDBId);
logger.info("SECRET FROM DB : " + clientFromDB.getSecret());
logger.info("SECRET FROM CACHE : " + clientFromCache.getSecret());

View file

@ -141,7 +141,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
clientStorage.setParentId(realm.getId());
clientStorageComponent = realm.addComponentModel(clientStorage);
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
Assert.assertNotNull(hardcodedClient);
@ -183,7 +183,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
Assert.assertNotNull("Created Date should be set", maryConsent.getCreatedDate());
Assert.assertNotNull("Last Updated Date should be set", maryConsent.getLastUpdatedDate());
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
UserConsentModel maryHardcodedConsent = currentSession.users().getConsentByClient(realm, mary.getId(), hardcodedClient.getId());
Assert.assertEquals(maryHardcodedConsent.getGrantedClientScopes().size(), 0);
Assert.assertNotNull("Created Date should be set", maryHardcodedConsent.getCreatedDate());
@ -210,7 +210,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
List<UserConsentModel> johnConsents = currentSession.users().getConsents(realm, john.getId());
Assert.assertEquals(2, johnConsents.size());
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
List<UserConsentModel> maryConsents = currentSession.users().getConsents(realm, mary.getId());
Assert.assertEquals(2, maryConsents.size());
@ -277,7 +277,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
UserModel mary = currentSession.users().getUserByUsername("mary", realm);
currentSession.users().revokeConsentForClient(realm, john.getId(), fooClient.getId());
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
currentSession.users().revokeConsentForClient(realm, mary.getId(), hardcodedClient.getId());
});
@ -286,7 +286,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
RealmModel realm = currentSession.realms().getRealm("original");
ClientModel fooClient = realm.getClientByClientId("foo-client");
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
UserModel john = currentSession.users().getUserByUsername("john", realm);
Assert.assertNull(currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()));
@ -384,7 +384,7 @@ public class UserConsentModelTest extends AbstractTestRealmKeycloakTest {
KeycloakSession currentSession = sessionCST2;
RealmModel realm = currentSession.realms().getRealm("original");
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
Assert.assertNull(hardcodedClient);
UserModel mary = currentSession.users().getUserByUsername("mary", realm);

View file

@ -152,7 +152,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo
clientStorage.setParentId(realm.getId());
clientStorageComponent = realm.addComponentModel(clientStorage);
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
Assert.assertNotNull(hardcodedClient);
@ -193,7 +193,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo
Assert.assertNotNull("Created Date should be set", maryConsent.getCreatedDate());
Assert.assertNotNull("Last Updated Date should be set", maryConsent.getLastUpdatedDate());
ClientModel hardcodedClient = currentSessionCT.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSessionCT.clients().getClientByClientId(realm, "hardcoded-client");
UserConsentModel maryHardcodedConsent = currentSession.users().getConsentByClient(realm, mary.getId(), hardcodedClient.getId());
Assert.assertEquals(maryHardcodedConsent.getGrantedClientScopes().size(), 0);
Assert.assertNotNull("Created Date should be set", maryHardcodedConsent.getCreatedDate());
@ -220,7 +220,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo
List<UserConsentModel> johnConsents = currentSession.users().getConsents(realm, john.getId());
Assert.assertEquals(2, johnConsents.size());
ClientModel hardcodedClient = currentSessionACT.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSessionACT.clients().getClientByClientId(realm, "hardcoded-client");
List<UserConsentModel> maryConsents = currentSession.users().getConsents(realm, mary.getId());
Assert.assertEquals(2, maryConsents.size());
@ -287,7 +287,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo
UserModel mary = currentSession.users().getUserByUsername("mary", realm);
currentSession.users().revokeConsentForClient(realm, john.getId(), fooClient.getId());
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
currentSession.users().revokeConsentForClient(realm, mary.getId(), hardcodedClient.getId());
});
@ -296,7 +296,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo
RealmModel realm = currentSession.realms().getRealmByName("original");
ClientModel fooClient = realm.getClientByClientId("foo-client");
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
UserModel john = currentSession.users().getUserByUsername("john", realm);
Assert.assertNull(currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId()));
@ -396,7 +396,7 @@ public class UserConsentWithUserStorageModelTest extends AbstractTestRealmKeyclo
KeycloakSession currentSession = sesDelClientStore2;
RealmModel realm = currentSession.realms().getRealmByName("original");
ClientModel hardcodedClient = currentSession.realms().getClientByClientId("hardcoded-client", realm);
ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
Assert.assertNull(hardcodedClient);
UserModel mary = currentSession.users().getUserByUsername("mary", realm);

View file

@ -102,49 +102,49 @@ public class OAuthRedirectUriTest extends AbstractKeycloakTest {
RealmRepresentation realmRepresentation = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
RealmBuilder realm = RealmBuilder.edit(realmRepresentation).testEventListener();
ClientBuilder installedApp = ClientBuilder.create().id("test-installed").name("test-installed")
ClientBuilder installedApp = ClientBuilder.create().clientId("test-installed").name("test-installed")
.redirectUris(Constants.INSTALLED_APP_URN, Constants.INSTALLED_APP_URL)
.secret("password");
realm.client(installedApp);
ClientBuilder installedApp2 = ClientBuilder.create().id("test-installed2").name("test-installed2")
ClientBuilder installedApp2 = ClientBuilder.create().clientId("test-installed2").name("test-installed2")
.redirectUris(Constants.INSTALLED_APP_URL + "/myapp")
.secret("password");
realm.client(installedApp2);
ClientBuilder installedApp3 = ClientBuilder.create().id("test-wildcard").name("test-wildcard")
ClientBuilder installedApp3 = ClientBuilder.create().clientId("test-wildcard").name("test-wildcard")
.redirectUris("http://example.com/foo/*", "http://with-dash.example.local/foo/*", "http://localhost:8280/foo/*")
.secret("password");
realm.client(installedApp3);
ClientBuilder installedApp4 = ClientBuilder.create().id("test-dash").name("test-dash")
ClientBuilder installedApp4 = ClientBuilder.create().clientId("test-dash").name("test-dash")
.redirectUris("http://with-dash.example.local", "http://with-dash.example.local/foo")
.secret("password");
realm.client(installedApp4);
ClientBuilder installedApp5 = ClientBuilder.create().id("test-root-url").name("test-root-url")
ClientBuilder installedApp5 = ClientBuilder.create().clientId("test-root-url").name("test-root-url")
.rootUrl("http://with-dash.example.local")
.redirectUris("/foo")
.secret("password");
realm.client(installedApp5);
ClientBuilder installedApp6 = ClientBuilder.create().id("test-relative-url").name("test-relative-url")
ClientBuilder installedApp6 = ClientBuilder.create().clientId("test-relative-url").name("test-relative-url")
.rootUrl("")
.redirectUris("/auth")
.secret("password");
realm.client(installedApp6);
ClientBuilder installedApp7 = ClientBuilder.create().id("test-query-component").name("test-query-component")
ClientBuilder installedApp7 = ClientBuilder.create().clientId("test-query-component").name("test-query-component")
.redirectUris("http://localhost?foo=bar", "http://localhost?foo=bar*")
.secret("password");
realm.client(installedApp7);
ClientBuilder installedApp8 = ClientBuilder.create().id("test-fragment").name("test-fragment")
ClientBuilder installedApp8 = ClientBuilder.create().clientId("test-fragment").name("test-fragment")
.redirectUris("http://localhost:8180/*", "https://localhost:8543/*")
.secret("password");
realm.client(installedApp8);
ClientBuilder installedAppCustomScheme = ClientBuilder.create().id("custom-scheme").name("custom-scheme")
ClientBuilder installedAppCustomScheme = ClientBuilder.create().clientId("custom-scheme").name("custom-scheme")
.redirectUris("android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login")
.secret("password");
realm.client(installedAppCustomScheme);

View file

@ -41,7 +41,7 @@ public class TokenEndpointCorsTest extends AbstractKeycloakTest {
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).id("test-app2").clientId("test-app2").publicClient().directAccessGrants().build());
realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).clientId("test-app2").publicClient().directAccessGrants().build());
testRealms.add(realm);
}

View file

@ -48,7 +48,7 @@ public class TokenRevocationCorsTest extends AbstractKeycloakTest {
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app")
.addWebOrigin(VALID_CORS_URL).id("test-app2").clientId("test-app2").publicClient().directAccessGrants().build());
.addWebOrigin(VALID_CORS_URL).clientId("test-app2").publicClient().directAccessGrants().build());
testRealms.add(realm);
}

View file

@ -28,7 +28,7 @@ public class UserInfoEndpointCorsTest extends AbstractKeycloakTest {
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).id("test-app2").clientId("test-app2").publicClient().directAccessGrants().build());
realm.getClients().add(ClientBuilder.create().redirectUris(VALID_CORS_URL + "/realms/master/app").addWebOrigin(VALID_CORS_URL).clientId("test-app2").publicClient().directAccessGrants().build());
testRealms.add(realm);
}

View file

@ -206,14 +206,16 @@ public class OpenShiftTokenReviewEndpointTest extends AbstractTestRealmKeycloakT
public void customScopes() {
ClientScopeRepresentation clientScope = new ClientScopeRepresentation();
clientScope.setProtocol("openid-connect");
clientScope.setId("user:info");
clientScope.setName("user:info");
testRealm().clientScopes().create(clientScope);
String id;
try (Response r = testRealm().clientScopes().create(clientScope)) {
id = ApiUtil.getCreatedId(r);
}
ClientRepresentation clientRep = testRealm().clients().findByClientId("test-app").get(0);
testRealm().clients().get(clientRep.getId()).addOptionalClientScope("user:info");
testRealm().clients().get(clientRep.getId()).addOptionalClientScope(id);
try {
oauth.scope("user:info");
@ -221,7 +223,7 @@ public class OpenShiftTokenReviewEndpointTest extends AbstractTestRealmKeycloakT
.invoke()
.assertSuccess().assertScope("openid", "user:info", "profile", "email");
} finally {
testRealm().clients().get(clientRep.getId()).removeOptionalClientScope("user:info");
testRealm().clients().get(clientRep.getId()).removeOptionalClientScope(id);
}
}

View file

@ -1,6 +1,5 @@
package org.keycloak.testsuite.saml;
import org.keycloak.protocol.saml.SamlClient;
import org.keycloak.protocol.saml.SamlConfigAttributes;
import org.keycloak.protocol.saml.SamlProtocol;
import org.junit.Test;

View file

@ -97,7 +97,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {
.idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build()
.login().user(bburkeUser).build()
.processSamlResponse(SamlClient.Binding.POST)
.transformObject(r -> { checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); })
.transformObject(r -> { return checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); })
.build()
.execute();
}
@ -116,7 +116,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {
.idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build()
.login().user(bburkeUser).build()
.processSamlResponse(SamlClient.Binding.POST)
.transformObject(r -> { checkSessionNotOnOrAfter(r, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); })
.transformObject(r -> { return checkSessionNotOnOrAfter(r, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); })
.build()
.execute();
}
@ -136,7 +136,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {
.build()
.login().user(bburkeUser).build()
.processSamlResponse(SamlClient.Binding.POST)
.transformObject(r -> { checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); })
.transformObject(r -> { return checkSessionNotOnOrAfter(r, SSO_MAX_LIFESPAN, ACCESS_CODE_LIFESPAN, ACCESS_TOKEN_LIFESPAN); })
.build()
.execute();
}
@ -152,7 +152,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {
.idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build()
.login().user(bburkeUser).build()
.processSamlResponse(SamlClient.Binding.POST)
.transformObject(r -> { checkSessionNotOnOrAfter(r, ssoMaxLifespan, 2000, 2000); })
.transformObject(r -> { return checkSessionNotOnOrAfter(r, ssoMaxLifespan, 2000, 2000); })
.build()
.execute();
}
@ -169,7 +169,7 @@ public class SessionNotOnOrAfterTest extends AbstractSamlTest {
.build()
.login().user(bburkeUser).build()
.processSamlResponse(SamlClient.Binding.POST)
.transformObject(r -> { checkSessionNotOnOrAfter(r, ssoMaxLifespan, 1800, 1800); })
.transformObject(r -> { return checkSessionNotOnOrAfter(r, ssoMaxLifespan, 1800, 1800); })
.build()
.execute();
}

View file

@ -17,16 +17,12 @@
package org.keycloak.testsuite.util.cli;
import java.util.HashSet;
import java.util.Set;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionTask;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.utils.KeycloakModelUtils;
/**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
@ -83,7 +79,7 @@ public class RoleCommands {
return realm;
} else {
String clientId = parts[1];
ClientModel client = session.realms().getClientByClientId(clientId, realm);
ClientModel client = session.clients().getClientByClientId(realm, clientId);
if (client == null) {
log.errorf("Unknown client: %s", clientId);
throw new HandledException();