Authorization services refactoring

Closes: #10447 

* Prepare logical layer to distinguish between ResourceServer id and client.id
* Reorder Authz methods: For entities outside of Authz we use RealmModel as first parameter for each method, to be consistent with this we move ResourceServer to the first place for each method in authz
* Prepare Logical (Models/Adapters) layer for returning other models instead of ids
* Replace resourceServerId with resourceServer model in PermissionTicketStore
* Replace resourceServerId with resourceServer model in PolicyStore
* Replace resourceServerId with resourceServer model in ScopeStore
* Replace resourceServerId with resourceServer model in ResourceStore
* Fix PermissionTicketStore bug
* Fix NPEs in caching layer
* Replace primitive int with Integer for pagination parameters
This commit is contained in:
Michal Hajas 2022-03-22 20:49:40 +01:00 committed by GitHub
parent c0255cbeea
commit 99c06d1102
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
79 changed files with 1257 additions and 1139 deletions

View file

@ -112,7 +112,7 @@ public class ClientPolicyProviderFactory implements PolicyProviderFactory<Client
ResourceServer resourceServer = resourceServerStore.findByClient(removedClient);
if (resourceServer != null) {
policyStore.findByType(getId(), resourceServer.getId()).forEach(policy -> {
policyStore.findByType(resourceServer, getId()).forEach(policy -> {
List<String> clients = new ArrayList<>();
for (String clientId : getClients(policy)) {

View file

@ -74,7 +74,7 @@ public class ClientScopePolicyProviderFactory implements PolicyProviderFactory<C
filters.put(Policy.FilterOption.TYPE, new String[] { getId() });
policyStore.findByResourceServer(filters, null, -1, -1).forEach(new Consumer<Policy>() {
policyStore.findByResourceServer(null, filters, null, null).forEach(new Consumer<Policy>() {
@Override
public void accept(Policy policy) {

View file

@ -28,7 +28,6 @@ import org.keycloak.authorization.policy.provider.PolicyProvider;
import org.keycloak.authorization.policy.provider.PolicyProviderFactory;
import org.keycloak.authorization.store.PolicyStore;
import org.keycloak.models.ClientModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel;
@ -397,7 +396,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
rep.setName(KeycloakModelUtils.generateId());
rep.setCode(condition);
Policy associatedPolicy = policyStore.create(rep, policy.getResourceServer());
Policy associatedPolicy = policyStore.create(policy.getResourceServer(), rep);
associatedPolicy.setOwner(owner);
@ -410,7 +409,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
rep.setName(KeycloakModelUtils.generateId());
rep.addClient(client);
Policy associatedPolicy = policyStore.create(rep, policy.getResourceServer());
Policy associatedPolicy = policyStore.create(policy.getResourceServer(), rep);
associatedPolicy.setOwner(owner);
@ -423,7 +422,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
rep.setName(KeycloakModelUtils.generateId());
rep.addGroupPath(group);
Policy associatedPolicy = policyStore.create(rep, policy.getResourceServer());
Policy associatedPolicy = policyStore.create(policy.getResourceServer(), rep);
associatedPolicy.setOwner(owner);
@ -436,7 +435,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
rep.setName(KeycloakModelUtils.generateId());
rep.addRole(role, false);
Policy associatedPolicy = policyStore.create(rep, policy.getResourceServer());
Policy associatedPolicy = policyStore.create(policy.getResourceServer(), rep);
associatedPolicy.setOwner(owner);
@ -449,7 +448,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
rep.setName(KeycloakModelUtils.generateId());
rep.addUser(user);
Policy associatedPolicy = policyStore.create(rep, policy.getResourceServer());
Policy associatedPolicy = policyStore.create(policy.getResourceServer(), rep);
associatedPolicy.setOwner(owner);

View file

@ -223,7 +223,7 @@ public class RolePolicyProviderFactory implements PolicyProviderFactory<RolePoli
ResourceServer resourceServer = resourceServerStore.findByClient(clientModel);
if (resourceServer != null) {
policyStore.findByType(getId(), resourceServer.getId()).forEach(policy -> {
policyStore.findByType(resourceServer, getId()).forEach(policy -> {
List<Map> roles = new ArrayList<>();
for (Map<String,Object> role : getRoles(policy)) {

View file

@ -42,7 +42,8 @@ public class PermissionTicketAdapter implements PermissionTicket, CachedModel<Pe
@Override
public PermissionTicket getDelegateForUpdate() {
if (updated == null) {
updated = cacheSession.getPermissionTicketStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
ResourceServer resourceServer = cacheSession.getResourceServerStoreDelegate().findById(cached.getResourceServerId());
updated = cacheSession.getPermissionTicketStoreDelegate().findById(resourceServer, cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
cacheSession.registerPermissionTicketInvalidation(cached.getId(), cached.getOwner(), cached.getRequester(), cached.getResourceId(), updated.getResource().getName(), cached.getScopeId(), cached.getResourceServerId());
}
@ -69,7 +70,8 @@ public class PermissionTicketAdapter implements PermissionTicket, CachedModel<Pe
protected boolean isUpdated() {
if (updated != null) return true;
if (!invalidated) return false;
updated = cacheSession.getPermissionTicketStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
ResourceServer resourceServer = cacheSession.getResourceServerStoreDelegate().findById(cached.getResourceServerId());
updated = cacheSession.getPermissionTicketStoreDelegate().findById(resourceServer, cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
return true;
}
@ -126,7 +128,7 @@ public class PermissionTicketAdapter implements PermissionTicket, CachedModel<Pe
@Override
public Policy getPolicy() {
if (isUpdated()) return updated.getPolicy();
return cacheSession.getPolicyStore().findById(cached.getPolicy(), cached.getResourceServerId());
return cacheSession.getPolicyStore().findById(cacheSession.getResourceServerStore().findById(cached.getResourceServerId()), cached.getPolicy());
}
@Override
@ -138,12 +140,12 @@ public class PermissionTicketAdapter implements PermissionTicket, CachedModel<Pe
@Override
public Resource getResource() {
return cacheSession.getResourceStore().findById(cached.getResourceId(), getResourceServer().getId());
return cacheSession.getResourceStore().findById(getResourceServer(), cached.getResourceId());
}
@Override
public Scope getScope() {
return cacheSession.getScopeStore().findById(cached.getScopeId(), getResourceServer().getId());
return cacheSession.getScopeStore().findById(getResourceServer(), cached.getScopeId());
}
@Override

View file

@ -85,7 +85,7 @@ public class PolicyAdapter implements Policy, CachedModel<Policy> {
protected boolean isUpdated() {
if (updated != null) return true;
if (!invalidated) return false;
updated = cacheSession.getPolicyStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
updated = cacheSession.getPolicyStoreDelegate().findById(cacheSession.getResourceServerStore().findById(cached.getResourceServerId()), cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
return true;
}
@ -208,7 +208,7 @@ public class PolicyAdapter implements Policy, CachedModel<Policy> {
PolicyStore policyStore = cacheSession.getPolicyStore();
String resourceServerId = cached.getResourceServerId();
for (String id : cached.getAssociatedPoliciesIds(modelSupplier)) {
Policy policy = policyStore.findById(id, resourceServerId);
Policy policy = policyStore.findById(cacheSession.getResourceServerStore().findById(resourceServerId), id);
cacheSession.cachePolicy(policy);
associatedPolicies.add(policy);
}
@ -223,9 +223,9 @@ public class PolicyAdapter implements Policy, CachedModel<Policy> {
if (resources != null) return resources;
resources = new HashSet<>();
ResourceStore resourceStore = cacheSession.getResourceStore();
ResourceServer resourceServer = getResourceServer();
for (String resourceId : cached.getResourcesIds(modelSupplier)) {
String resourceServerId = cached.getResourceServerId();
Resource resource = resourceStore.findById(resourceId, resourceServerId);
Resource resource = resourceStore.findById(resourceServer, resourceId);
cacheSession.cacheResource(resource);
resources.add(resource);
}
@ -287,10 +287,10 @@ public class PolicyAdapter implements Policy, CachedModel<Policy> {
if (isUpdated()) return updated.getScopes();
if (scopes != null) return scopes;
scopes = new HashSet<>();
ResourceServer resourceServer = getResourceServer();
ScopeStore scopeStore = cacheSession.getScopeStore();
String resourceServerId = cached.getResourceServerId();
for (String scopeId : cached.getScopesIds(modelSupplier)) {
Scope scope = scopeStore.findById(scopeId, resourceServerId);
Scope scope = scopeStore.findById(resourceServer, scopeId);
cacheSession.cacheScope(scope);
scopes.add(scope);
}
@ -325,6 +325,6 @@ public class PolicyAdapter implements Policy, CachedModel<Policy> {
}
private Policy getPolicyModel() {
return cacheSession.getPolicyStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
return cacheSession.getPolicyStoreDelegate().findById(cacheSession.getResourceServerStore().findById(cached.getResourceServerId()), cached.getId());
}
}

View file

@ -81,7 +81,7 @@ public class ResourceAdapter implements Resource, CachedModel<Resource> {
protected boolean isUpdated() {
if (updated != null) return true;
if (!invalidated) return false;
updated = cacheSession.getResourceStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
updated = cacheSession.getResourceStoreDelegate().findById(getResourceServer(), cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
return true;
}
@ -133,9 +133,8 @@ public class ResourceAdapter implements Resource, CachedModel<Resource> {
}
@Override
public String getResourceServer() {
if (isUpdated()) return updated.getResourceServer();
return cached.getResourceServerId();
public ResourceServer getResourceServer() {
return cacheSession.getResourceServerStoreDelegate().findById(cached.getResourceServerId());
}
@Override
@ -173,7 +172,7 @@ public class ResourceAdapter implements Resource, CachedModel<Resource> {
if (scopes != null) return scopes;
scopes = new LinkedList<>();
for (String scopeId : cached.getScopesIds(modelSupplier)) {
scopes.add(cacheSession.getScopeStore().findById(scopeId, cached.getResourceServerId()));
scopes.add(cacheSession.getScopeStore().findById(getResourceServer(), scopeId));
}
return scopes = Collections.unmodifiableList(scopes);
}
@ -204,7 +203,7 @@ public class ResourceAdapter implements Resource, CachedModel<Resource> {
for (Scope scope : updated.getScopes()) {
if (!scopes.contains(scope)) {
PermissionTicketStore permissionStore = cacheSession.getPermissionTicketStore();
List<PermissionTicket> permissions = permissionStore.findByScope(scope.getId(), getResourceServer());
List<PermissionTicket> permissions = permissionStore.findByScope(getResourceServer(), scope);
for (PermissionTicket permission : permissions) {
permissionStore.delete(permission.getId());
@ -216,7 +215,7 @@ public class ResourceAdapter implements Resource, CachedModel<Resource> {
for (Scope scope : updated.getScopes()) {
if (!scopes.contains(scope)) {
policyStore.findByResource(getId(), getResourceServer(), policy -> policy.removeScope(scope));
policyStore.findByResource(getResourceServer(), this, policy -> policy.removeScope(scope));
}
}
@ -283,6 +282,6 @@ public class ResourceAdapter implements Resource, CachedModel<Resource> {
}
private Resource getResourceModel() {
return cacheSession.getResourceStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
return cacheSession.getResourceStoreDelegate().findById(getResourceServer(), cached.getId());
}
}

View file

@ -39,7 +39,7 @@ public class ScopeAdapter implements Scope, CachedModel<Scope> {
public Scope getDelegateForUpdate() {
if (updated == null) {
cacheSession.registerScopeInvalidation(cached.getId(), cached.getName(), cached.getResourceServerId());
updated = cacheSession.getScopeStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
updated = cacheSession.getScopeStoreDelegate().findById(getResourceServer(), cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
}
return updated;
@ -66,7 +66,7 @@ public class ScopeAdapter implements Scope, CachedModel<Scope> {
protected boolean isUpdated() {
if (updated != null) return true;
if (!invalidated) return false;
updated = cacheSession.getScopeStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
updated = cacheSession.getScopeStoreDelegate().findById(getResourceServer(), cached.getId());
if (updated == null) throw new IllegalStateException("Not found in database");
return true;
}

View file

@ -309,8 +309,9 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
return Collections.emptySet();
}
ResourceServer resourceServer = getResourceServerStore().findById(serverId);
return resources.stream().map(resourceId -> {
Resource resource = getResourceStore().findById(resourceId, serverId);
Resource resource = getResourceStore().findById(resourceServer, resourceId);
String type = resource.getType();
if (type != null) {
@ -496,13 +497,13 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
protected class ScopeCache implements ScopeStore {
@Override
public Scope create(String name, ResourceServer resourceServer) {
return create(null, name, resourceServer);
public Scope create(ResourceServer resourceServer, String name) {
return create(resourceServer, null, name);
}
@Override
public Scope create(String id, String name, ResourceServer resourceServer) {
Scope scope = getScopeStoreDelegate().create(id, name, resourceServer);
public Scope create(ResourceServer resourceServer, String id, String name) {
Scope scope = getScopeStoreDelegate().create(resourceServer, id, name);
registerScopeInvalidation(scope.getId(), scope.getName(), resourceServer.getId());
return scope;
}
@ -510,7 +511,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
@Override
public void delete(String id) {
if (id == null) return;
Scope scope = findById(id, null);
Scope scope = findById(null, id);
if (scope == null) return;
cache.invalidateObject(id);
@ -520,7 +521,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public Scope findById(String id, String resourceServerId) {
public Scope findById(ResourceServer resourceServer, String id) {
if (id == null) return null;
CachedScope cached = cache.get(id, CachedScope.class);
if (cached != null) {
@ -529,7 +530,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
if (cached == null) {
Long loaded = cache.getCurrentRevision(id);
if (! modelMightExist(id)) return null;
Scope model = getScopeStoreDelegate().findById(id, resourceServerId);
Scope model = getScopeStoreDelegate().findById(resourceServer, id);
if (model == null) {
setModelDoesNotExists(id, loaded);
return null;
@ -538,7 +539,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
cached = new CachedScope(loaded, model);
cache.addRevisioned(cached, startupRevision);
} else if (invalidations.contains(id)) {
return getScopeStoreDelegate().findById(id, resourceServerId);
return getScopeStoreDelegate().findById(resourceServer, id);
} else if (managedScopes.containsKey(id)) {
return managedScopes.get(id);
}
@ -548,8 +549,9 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public Scope findByName(String name, String resourceServerId) {
public Scope findByName(ResourceServer resourceServer, String name) {
if (name == null) return null;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getScopeByNameCacheKey(name, resourceServerId);
ScopeListQuery query = cache.get(cacheKey, ScopeListQuery.class);
if (query != null) {
@ -557,43 +559,43 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
if (query == null) {
Long loaded = cache.getCurrentRevision(cacheKey);
Scope model = getScopeStoreDelegate().findByName(name, resourceServerId);
Scope model = getScopeStoreDelegate().findByName(resourceServer, name);
if (model == null) return null;
if (invalidations.contains(model.getId())) return model;
query = new ScopeListQuery(loaded, cacheKey, model.getId(), resourceServerId);
cache.addRevisioned(query, startupRevision);
return model;
} else if (invalidations.contains(cacheKey)) {
return getScopeStoreDelegate().findByName(name, resourceServerId);
return getScopeStoreDelegate().findByName(resourceServer, name);
} else {
String id = query.getScopes().iterator().next();
if (invalidations.contains(id)) {
return getScopeStoreDelegate().findByName(name, resourceServerId);
return getScopeStoreDelegate().findByName(resourceServer, name);
}
return findById(id, query.getResourceServerId());
return findById(resourceServer, id);
}
}
@Override
public List<Scope> findByResourceServer(String id) {
return getScopeStoreDelegate().findByResourceServer(id);
public List<Scope> findByResourceServer(ResourceServer resourceServer) {
return getScopeStoreDelegate().findByResourceServer(resourceServer);
}
@Override
public List<Scope> findByResourceServer(Map<Scope.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
return getScopeStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
public List<Scope> findByResourceServer(ResourceServer resourceServer, Map<Scope.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
return getScopeStoreDelegate().findByResourceServer(resourceServer, attributes, firstResult, maxResults);
}
}
protected class ResourceCache implements ResourceStore {
@Override
public Resource create(String id, String name, ResourceServer resourceServer, String owner) {
Resource resource = getResourceStoreDelegate().create(id, name, resourceServer, owner);
Resource cached = findById(resource.getId(), resourceServer.getId());
registerResourceInvalidation(resource.getId(), resource.getName(), resource.getType(), resource.getUris(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resourceServer.getId(), resource.getOwner());
public Resource create(ResourceServer resourceServer, String id, String name, String owner) {
Resource resource = getResourceStoreDelegate().create(resourceServer, id, name, owner);
Resource cached = findById(resourceServer, resource.getId());
registerResourceInvalidation(resource.getId(), resource.getName(), resource.getType(), resource.getUris(), resource.getScopes().stream().map(Scope::getId).collect(Collectors.toSet()), resourceServer.getId(), resource.getOwner());
if (cached == null) {
cached = findById(resource.getId(), resourceServer.getId());
cached = findById(resourceServer, resource.getId());
}
return cached;
}
@ -601,18 +603,18 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
@Override
public void delete(String id) {
if (id == null) return;
Resource resource = findById(id, null);
Resource resource = findById(null, id);
if (resource == null) return;
cache.invalidateObject(id);
invalidationEvents.add(ResourceRemovedEvent.create(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resource.getResourceServer()));
cache.resourceRemoval(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resource.getResourceServer(), invalidations);
invalidationEvents.add(ResourceRemovedEvent.create(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(Scope::getId).collect(Collectors.toSet()), resource.getResourceServer().getId()));
cache.resourceRemoval(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(Scope::getId).collect(Collectors.toSet()), resource.getResourceServer().getId(), invalidations);
getResourceStoreDelegate().delete(id);
}
@Override
public Resource findById(String id, String resourceServerId) {
public Resource findById(ResourceServer resourceServer, String id) {
if (id == null) return null;
CachedResource cached = cache.get(id, CachedResource.class);
if (cached != null) {
@ -621,7 +623,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
if (cached == null) {
Long loaded = cache.getCurrentRevision(id);
if (! modelMightExist(id)) return null;
Resource model = getResourceStoreDelegate().findById(id, resourceServerId);
Resource model = getResourceStoreDelegate().findById(resourceServer, id);
if (model == null) {
setModelDoesNotExists(id, loaded);
return null;
@ -630,7 +632,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
cached = new CachedResource(loaded, model);
cache.addRevisioned(cached, startupRevision);
} else if (invalidations.contains(id)) {
return getResourceStoreDelegate().findById(id, resourceServerId);
return getResourceStoreDelegate().findById(resourceServer, id);
} else if (managedResources.containsKey(id)) {
return managedResources.get(id);
}
@ -640,16 +642,12 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public Resource findByName(String name, String resourceServerId) {
return findByName(name, resourceServerId, resourceServerId);
}
@Override
public Resource findByName(String name, String ownerId, String resourceServerId) {
public Resource findByName(ResourceServer resourceServer, String name, String ownerId) {
if (name == null) return null;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByNameCacheKey(name, ownerId, resourceServerId);
List<Resource> result = cacheQuery(cacheKey, ResourceListQuery.class, () -> {
Resource resource = getResourceStoreDelegate().findByName(name, ownerId, resourceServerId);
Resource resource = getResourceStoreDelegate().findByName(resourceServer, name, ownerId);
if (resource == null) {
return Collections.emptyList();
@ -657,7 +655,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
return Arrays.asList(resource);
},
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServerId);
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
if (result.isEmpty()) {
return null;
@ -667,18 +665,20 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public List<Resource> findByOwner(String ownerId, String resourceServerId) {
public List<Resource> findByOwner(ResourceServer resourceServer, String ownerId) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByOwnerCacheKey(ownerId, resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByOwner(ownerId, resourceServerId),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByOwner(resourceServer, ownerId),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer) {
public void findByOwner(ResourceServer resourceServer, String ownerId, Consumer<Resource> consumer) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByOwnerCacheKey(ownerId, resourceServerId);
cacheQuery(cacheKey, ResourceListQuery.class, () -> {
List<Resource> resources = new ArrayList<>();
getResourceStoreDelegate().findByOwner(ownerId, resourceServerId, new Consumer<Resource>() {
getResourceStoreDelegate().findByOwner(resourceServer, ownerId, new Consumer<Resource>() {
@Override
public void accept(Resource resource) {
consumer.andThen(resources::add)
@ -688,54 +688,57 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
});
return resources;
},
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
@Override
public List<Resource> findByOwner(String ownerId, String resourceServerId, int first, int max) {
return getResourceStoreDelegate().findByOwner(ownerId, resourceServerId, first, max);
public List<Resource> findByOwner(ResourceServer resourceServer, String ownerId, Integer firstResult, Integer maxResults) {
return getResourceStoreDelegate().findByOwner(resourceServer, ownerId, firstResult, maxResults);
}
@Override
public List<Resource> findByUri(String uri, String resourceServerId) {
public List<Resource> findByUri(ResourceServer resourceServer, String uri) {
if (uri == null) return null;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByUriCacheKey(uri, resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByUri(uri, resourceServerId),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByUri(resourceServer, uri),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public List<Resource> findByResourceServer(String resourceServerId) {
return getResourceStoreDelegate().findByResourceServer(resourceServerId);
public List<Resource> findByResourceServer(ResourceServer resourceServer) {
return getResourceStoreDelegate().findByResourceServer(resourceServer);
}
@Override
public List<Resource> findByResourceServer(Map<Resource.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
return getResourceStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
public List<Resource> findByResourceServer(ResourceServer resourceServer, Map<Resource.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
return getResourceStoreDelegate().findByResourceServer(resourceServer, attributes, firstResult, maxResults);
}
@Override
public List<Resource> findByScope(List<String> ids, String resourceServerId) {
if (ids == null) return null;
public List<Resource> findByScopes(ResourceServer resourceServer, Set<Scope> scopes) {
if (scopes == null) return null;
List<Resource> result = new ArrayList<>();
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
for (String id : ids) {
String cacheKey = getResourceByScopeCacheKey(id, resourceServerId);
result.addAll(cacheQuery(cacheKey, ResourceScopeListQuery.class, () -> getResourceStoreDelegate().findByScope(Arrays.asList(id), resourceServerId), (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, id, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServerId));
for (Scope scope : scopes) {
String cacheKey = getResourceByScopeCacheKey(scope.getId(), resourceServerId);
result.addAll(cacheQuery(cacheKey, ResourceScopeListQuery.class, () -> getResourceStoreDelegate().findByScopes(resourceServer, Collections.singleton(scope)), (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, scope.getId(), resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer));
}
return result;
}
@Override
public void findByScope(List<String> ids, String resourceServerId, Consumer<Resource> consumer) {
if (ids == null) return;
public void findByScopes(ResourceServer resourceServer, Set<Scope> scopes, Consumer<Resource> consumer) {
if (scopes == null) return;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
for (String id : ids) {
String cacheKey = getResourceByScopeCacheKey(id, resourceServerId);
for (Scope scope : scopes) {
String cacheKey = getResourceByScopeCacheKey(scope.getId(), resourceServerId);
cacheQuery(cacheKey, ResourceScopeListQuery.class, () -> {
List<Resource> resources = new ArrayList<>();
getResourceStoreDelegate().findByScope(Arrays.asList(id), resourceServerId, new Consumer<Resource>() {
getResourceStoreDelegate().findByScopes(resourceServer, Collections.singleton(scope), new Consumer<Resource>() {
@Override
public void accept(Resource resource) {
consumer.andThen(resources::add)
@ -745,25 +748,27 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
});
return resources;
}, (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, id, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
}, (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, scope.getId(), resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
}
@Override
public List<Resource> findByType(String type, String resourceServerId) {
public List<Resource> findByType(ResourceServer resourceServer, String type) {
if (type == null) return Collections.emptyList();
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByTypeCacheKey(type, resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(type, resourceServerId),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(resourceServer, type),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public void findByType(String type, String resourceServerId, Consumer<Resource> consumer) {
public void findByType(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
if (type == null) return;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByTypeCacheKey(type, resourceServerId);
cacheQuery(cacheKey, ResourceListQuery.class, () -> {
List<Resource> resources = new ArrayList<>();
getResourceStoreDelegate().findByType(type, resourceServerId, new Consumer<Resource>() {
getResourceStoreDelegate().findByType(resourceServer, type, new Consumer<Resource>() {
@Override
public void accept(Resource resource) {
consumer.andThen(resources::add)
@ -773,28 +778,30 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
});
return resources;
},
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
@Override
public List<Resource> findByType(String type, String owner, String resourceServerId) {
if (resourceServerId.equals(owner)) {
return findByType(type, resourceServerId);
public List<Resource> findByType(ResourceServer resourceServer, String type, String owner) {
if (resourceServer != null && resourceServer.getId().equals(owner)) {
return findByType(resourceServer, type);
} else {
if (type == null) return Collections.emptyList();
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByTypeCacheKey(type, owner, resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(type, owner, resourceServerId),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(resourceServer, type, owner),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
}
@Override
public void findByType(String type, String owner, String resourceServerId, Consumer<Resource> consumer) {
public void findByType(ResourceServer resourceServer, String type, String owner, Consumer<Resource> consumer) {
if (type == null) return;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByTypeCacheKey(type, owner, resourceServerId);
cacheQuery(cacheKey, ResourceListQuery.class, () -> {
List<Resource> resources = new ArrayList<>();
getResourceStoreDelegate().findByType(type, owner, resourceServerId, new Consumer<Resource>() {
getResourceStoreDelegate().findByType(resourceServer, type, owner, new Consumer<Resource>() {
@Override
public void accept(Resource resource) {
consumer.andThen(resources::add)
@ -804,24 +811,26 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
});
return resources;
},
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
@Override
public List<Resource> findByTypeInstance(String type, String resourceServerId) {
public List<Resource> findByTypeInstance(ResourceServer resourceServer, String type) {
if (type == null) return Collections.emptyList();
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByTypeInstanceCacheKey(type, resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByTypeInstance(type, resourceServerId),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByTypeInstance(resourceServer, type),
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public void findByTypeInstance(String type, String resourceServerId, Consumer<Resource> consumer) {
public void findByTypeInstance(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
if (type == null) return;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getResourceByTypeInstanceCacheKey(type, resourceServerId);
cacheQuery(cacheKey, ResourceListQuery.class, () -> {
List<Resource> resources = new ArrayList<>();
getResourceStoreDelegate().findByTypeInstance(type, resourceServerId, new Consumer<Resource>() {
getResourceStoreDelegate().findByTypeInstance(resourceServer, type, new Consumer<Resource>() {
@Override
public void accept(Resource resource) {
consumer.andThen(resources::add)
@ -831,18 +840,18 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
});
return resources;
},
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
(revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(Resource::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServerId, consumer, false);
private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, ResourceServer resourceServer, Consumer<R> consumer) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServer, consumer, false);
}
private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServerId, null, true);
private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, ResourceServer resourceServer) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServer, null, true);
}
private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer, boolean cacheResult) {
private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, ResourceServer resourceServer, Consumer<R> consumer, boolean cacheResult) {
Q query = cache.get(cacheKey, queryType);
if (query != null) {
logger.tracev("cache hit for key: {0}", cacheKey);
@ -863,9 +872,9 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
Set<String> resources = query.getResources();
if (consumer != null) {
resources.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).forEach(consumer);
resources.stream().map(resourceId -> (R) findById(resourceServer, resourceId)).forEach(consumer);
} else {
model = resources.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
model = resources.stream().map(resourceId -> (R) findById(resourceServer, resourceId)).collect(Collectors.toList());
}
}
@ -879,12 +888,12 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
protected class PolicyCache implements PolicyStore {
@Override
public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
Policy policy = getPolicyStoreDelegate().create(representation, resourceServer);
Policy cached = findById(policy.getId(), resourceServer.getId());
public Policy create(ResourceServer resourceServer, AbstractPolicyRepresentation representation) {
Policy policy = getPolicyStoreDelegate().create(resourceServer, representation);
Policy cached = findById(resourceServer, policy.getId());
registerPolicyInvalidation(policy.getId(), representation.getName(), representation.getResources(), representation.getScopes(), null, resourceServer.getId());
if (cached == null) {
cached = findById(policy.getId(), resourceServer.getId());
cached = findById(resourceServer, policy.getId());
}
return cached;
}
@ -892,18 +901,18 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
@Override
public void delete(String id) {
if (id == null) return;
Policy policy = findById(id, null);
Policy policy = findById(null, id);
if (policy == null) return;
cache.invalidateObject(id);
Set<String> resources = policy.getResources().stream().map(resource -> resource.getId()).collect(Collectors.toSet());
Set<String> resources = policy.getResources().stream().map(Resource::getId).collect(Collectors.toSet());
ResourceServer resourceServer = policy.getResourceServer();
Set<String> resourceTypes = getResourceTypes(resources, resourceServer.getId());
String defaultResourceType = policy.getConfig().get("defaultResourceType");
if (Objects.nonNull(defaultResourceType)) {
resourceTypes.add(defaultResourceType);
}
Set<String> scopes = policy.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet());
Set<String> scopes = policy.getScopes().stream().map(Scope::getId).collect(Collectors.toSet());
invalidationEvents.add(PolicyRemovedEvent.create(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId()));
cache.policyRemoval(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId(), invalidations);
getPolicyStoreDelegate().delete(id);
@ -911,7 +920,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public Policy findById(String id, String resourceServerId) {
public Policy findById(ResourceServer resourceServer, String id) {
if (id == null) return null;
CachedPolicy cached = cache.get(id, CachedPolicy.class);
@ -920,7 +929,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
if (cached == null) {
if (! modelMightExist(id)) return null;
Policy model = getPolicyStoreDelegate().findById(id, resourceServerId);
Policy model = getPolicyStoreDelegate().findById(resourceServer, id);
Long loaded = cache.getCurrentRevision(id);
if (model == null) {
setModelDoesNotExists(id, loaded);
@ -930,7 +939,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
cached = new CachedPolicy(loaded, model);
cache.addRevisioned(cached, startupRevision);
} else if (invalidations.contains(id)) {
return getPolicyStoreDelegate().findById(id, resourceServerId);
return getPolicyStoreDelegate().findById(resourceServer, id);
} else if (managedPolicies.containsKey(id)) {
return managedPolicies.get(id);
}
@ -940,18 +949,19 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public Policy findByName(String name, String resourceServerId) {
public Policy findByName(ResourceServer resourceServer, String name) {
if (name == null) return null;
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPolicyByNameCacheKey(name, resourceServerId);
List<Policy> result = cacheQuery(cacheKey, PolicyListQuery.class, () -> {
Policy policy = getPolicyStoreDelegate().findByName(name, resourceServerId);
Policy policy = getPolicyStoreDelegate().findByName(resourceServer, name);
if (policy == null) {
return Collections.emptyList();
}
return Arrays.asList(policy);
}, (revision, policies) -> new PolicyListQuery(revision, cacheKey, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
}, (revision, policies) -> new PolicyListQuery(revision, cacheKey, policies.stream().map(Policy::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
if (result.isEmpty()) {
return null;
@ -961,28 +971,30 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public List<Policy> findByResourceServer(String resourceServerId) {
return getPolicyStoreDelegate().findByResourceServer(resourceServerId);
public List<Policy> findByResourceServer(ResourceServer resourceServer) {
return getPolicyStoreDelegate().findByResourceServer(resourceServer);
}
@Override
public List<Policy> findByResourceServer(Map<Policy.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
return getPolicyStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
public List<Policy> findByResourceServer(ResourceServer resourceServer, Map<Policy.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
return getPolicyStoreDelegate().findByResourceServer(resourceServer, attributes, firstResult, maxResults);
}
@Override
public List<Policy> findByResource(String resourceId, String resourceServerId) {
String cacheKey = getPolicyByResource(resourceId, resourceServerId);
return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResource(resourceId, resourceServerId),
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceId, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
public List<Policy> findByResource(ResourceServer resourceServer, Resource resource) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPolicyByResource(resource.getId(), resourceServerId);
return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResource(resourceServer, resource),
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resource.getId(), policies.stream().map(Policy::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
String cacheKey = getPolicyByResource(resourceId, resourceServerId);
public void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPolicyByResource(resource.getId(), resourceServerId);
cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> {
List<Policy> policies = new ArrayList<>();
getPolicyStoreDelegate().findByResource(resourceId, resourceServerId, new Consumer<Policy>() {
getPolicyStoreDelegate().findByResource(resourceServer, resource, new Consumer<Policy>() {
@Override
public void accept(Policy policy) {
consumer.andThen(policies::add)
@ -992,22 +1004,24 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
});
return policies;
},
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceId, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resource.getId(), policies.stream().map(Policy::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
@Override
public List<Policy> findByResourceType(String resourceType, String resourceServerId) {
public List<Policy> findByResourceType(ResourceServer resourceServer, String resourceType) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPolicyByResourceType(resourceType, resourceServerId);
return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResourceType(resourceType, resourceServerId),
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResourceType(resourceServer, resourceType),
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(Policy::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public void findByResourceType(String resourceType, String resourceServerId, Consumer<Policy> consumer) {
public void findByResourceType(ResourceServer resourceServer, String resourceType, Consumer<Policy> consumer) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPolicyByResourceType(resourceType, resourceServerId);
cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> {
List<Policy> policies = new ArrayList<>();
getPolicyStoreDelegate().findByResourceType(resourceType, resourceServerId, new Consumer<Policy>() {
getPolicyStoreDelegate().findByResourceType(resourceServer, resourceType, new Consumer<Policy>() {
@Override
public void accept(Policy policy) {
consumer.andThen(policies::add)
@ -1017,71 +1031,75 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
});
return policies;
},
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
(revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(Policy::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
@Override
public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
if (scopeIds == null) return null;
public List<Policy> findByScopes(ResourceServer resourceServer, List<Scope> scopes) {
if (scopes == null) return null;
Set<Policy> result = new HashSet<>();
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
for (String id : scopeIds) {
String cacheKey = getPolicyByScope(id, resourceServerId);
result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId));
for (Scope scope : scopes) {
String cacheKey = getPolicyByScope(scope.getId(), resourceServerId);
result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopes(resourceServer, Collections.singletonList(scope)), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, scope.getId(), resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServer));
}
return new ArrayList<>(result);
}
@Override
public List<Policy> findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId) {
if (scopeIds == null) return null;
public List<Policy> findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes) {
if (scopes == null) return null;
Set<Policy> result = new HashSet<>();
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
for (String id : scopeIds) {
String cacheKey = getPolicyByResourceScope(id, resourceId, resourceServerId);
result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceId, resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId));
for (Scope scope : scopes) {
String cacheKey = getPolicyByResourceScope(scope.getId(), resource.getId(), resourceServerId);
result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopes(resourceServer, resource, Collections.singletonList(scope)), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, scope.getId(), resources.stream().map(Policy::getId).collect(Collectors.toSet()), resourceServerId), resourceServer));
}
return new ArrayList<>(result);
}
@Override
public void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer) {
for (String id : scopeIds) {
String cacheKey = getPolicyByResourceScope(id, resourceId, resourceServerId);
public void findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes, Consumer<Policy> consumer) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String resourceId = resource == null ? null : resource.getId();
for (Scope scope : scopes) {
String cacheKey = getPolicyByResourceScope(scope.getId(), resourceId, resourceServerId);
cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> {
List<Policy> policies = new ArrayList<>();
getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceId, resourceServerId,
getPolicyStoreDelegate().findByScopes(resourceServer, resource, Collections.singletonList(scope),
policy -> {
consumer.andThen(policies::add)
.andThen(StoreFactoryCacheSession.this::cachePolicy)
.accept(policy);
});
return policies;
}, (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
}, (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, scope.getId(), resources.stream().map(Policy::getId).collect(Collectors.toSet()), resourceServerId), resourceServer, consumer);
}
}
@Override
public List<Policy> findByType(String type, String resourceServerId) {
return getPolicyStoreDelegate().findByType(type, resourceServerId);
public List<Policy> findByType(ResourceServer resourceServer, String type) {
return getPolicyStoreDelegate().findByType(resourceServer, type);
}
@Override
public List<Policy> findDependentPolicies(String id, String resourceServerId) {
return getPolicyStoreDelegate().findDependentPolicies(id, resourceServerId);
public List<Policy> findDependentPolicies(ResourceServer resourceServer, String id) {
return getPolicyStoreDelegate().findDependentPolicies(resourceServer, id);
}
private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServerId, null, true);
private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, ResourceServer resourceServer) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServer, null, true);
}
private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServerId, consumer, false);
private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, ResourceServer resourceServer, Consumer<R> consumer) {
return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServer, consumer, false);
}
private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer, boolean cacheResults) {
private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, ResourceServer resourceServer, Consumer<R> consumer, boolean cacheResults) {
Q query = cache.get(cacheKey, queryType);
if (query != null) {
logger.tracev("cache hit for key: {0}", cacheKey);
@ -1103,10 +1121,10 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
if (consumer != null) {
for (String id : policies) {
consumer.accept((R) findById(id, resourceServerId));
consumer.accept((R) findById(resourceServer, id));
}
} else {
model = policies.stream().map(resourceId -> (R) findById(resourceId, resourceServerId))
model = policies.stream().map(resourceId -> (R) findById(resourceServer, resourceId))
.filter(Objects::nonNull).collect(Collectors.toList());
}
}
@ -1119,21 +1137,21 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
protected class PermissionTicketCache implements PermissionTicketStore {
@Override
public long count(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId) {
return getPermissionTicketStoreDelegate().count(attributes, resourceServerId);
public long count(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes) {
return getPermissionTicketStoreDelegate().count(resourceServer, attributes);
}
@Override
public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
PermissionTicket created = getPermissionTicketStoreDelegate().create(resourceId, scopeId, requester, resourceServer);
registerPermissionTicketInvalidation(created.getId(), created.getOwner(), created.getRequester(), created.getResource().getId(), created.getResource().getName(), scopeId, created.getResourceServer().getId());
public PermissionTicket create(ResourceServer resourceServer, Resource resource, Scope scope, String requester) {
PermissionTicket created = getPermissionTicketStoreDelegate().create(resourceServer, resource, scope, requester);
registerPermissionTicketInvalidation(created.getId(), created.getOwner(), created.getRequester(), created.getResource().getId(), created.getResource().getName(), scope == null ? null : scope.getId(), created.getResourceServer().getId());
return created;
}
@Override
public void delete(String id) {
if (id == null) return;
PermissionTicket permission = findById(id, null);
PermissionTicket permission = findById(null, id);
if (permission == null) return;
cache.invalidateObject(id);
@ -1149,7 +1167,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public PermissionTicket findById(String id, String resourceServerId) {
public PermissionTicket findById(ResourceServer resourceServer, String id) {
if (id == null) return null;
CachedPermissionTicket cached = cache.get(id, CachedPermissionTicket.class);
@ -1159,7 +1177,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
if (cached == null) {
Long loaded = cache.getCurrentRevision(id);
if (! modelMightExist(id)) return null;
PermissionTicket model = getPermissionTicketStoreDelegate().findById(id, resourceServerId);
PermissionTicket model = getPermissionTicketStoreDelegate().findById(resourceServer, id);
if (model == null) {
setModelDoesNotExists(id, loaded);
return null;
@ -1168,7 +1186,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
cached = new CachedPermissionTicket(loaded, model);
cache.addRevisioned(cached, startupRevision);
} else if (invalidations.contains(id)) {
return getPermissionTicketStoreDelegate().findById(id, resourceServerId);
return getPermissionTicketStoreDelegate().findById(resourceServer, id);
} else if (managedPermissionTickets.containsKey(id)) {
return managedPermissionTickets.get(id);
}
@ -1178,61 +1196,66 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
}
@Override
public List<PermissionTicket> findByResourceServer(String resourceServerId) {
return getPermissionTicketStoreDelegate().findByResourceServer(resourceServerId);
public List<PermissionTicket> findByResourceServer(ResourceServer resourceServer) {
return getPermissionTicketStoreDelegate().findByResourceServer(resourceServer);
}
@Override
public List<PermissionTicket> findByResource(String resourceId, String resourceServerId) {
String cacheKey = getPermissionTicketByResource(resourceId, resourceServerId);
return cacheQuery(cacheKey, PermissionTicketResourceListQuery.class, () -> getPermissionTicketStoreDelegate().findByResource(resourceId, resourceServerId),
(revision, permissions) -> new PermissionTicketResourceListQuery(revision, cacheKey, resourceId, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
public List<PermissionTicket> findByResource(ResourceServer resourceServer, Resource resource) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPermissionTicketByResource(resource.getId(), resourceServerId);
return cacheQuery(cacheKey, PermissionTicketResourceListQuery.class, () -> getPermissionTicketStoreDelegate().findByResource(resourceServer, resource),
(revision, permissions) -> new PermissionTicketResourceListQuery(revision, cacheKey, resource.getId(), permissions.stream().map(PermissionTicket::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public List<PermissionTicket> findByScope(String scopeId, String resourceServerId) {
String cacheKey = getPermissionTicketByScope(scopeId, resourceServerId);
return cacheQuery(cacheKey, PermissionTicketScopeListQuery.class, () -> getPermissionTicketStoreDelegate().findByScope(scopeId, resourceServerId),
(revision, permissions) -> new PermissionTicketScopeListQuery(revision, cacheKey, scopeId, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
public List<PermissionTicket> findByScope(ResourceServer resourceServer, Scope scope) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPermissionTicketByScope(scope.getId(), resourceServerId);
return cacheQuery(cacheKey, PermissionTicketScopeListQuery.class, () -> getPermissionTicketStoreDelegate().findByScope(resourceServer, scope),
(revision, permissions) -> new PermissionTicketScopeListQuery(revision, cacheKey, scope.getId(), permissions.stream().map(PermissionTicket::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public List<PermissionTicket> find(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId, int firstResult, int maxResult) {
return getPermissionTicketStoreDelegate().find(attributes, resourceServerId, firstResult, maxResult);
public List<PermissionTicket> find(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes, Integer firstResult, Integer maxResult) {
return getPermissionTicketStoreDelegate().find(resourceServer, attributes, firstResult, maxResult);
}
@Override
public List<PermissionTicket> findGranted(String userId, String resourceServerId) {
public List<PermissionTicket> findGranted(ResourceServer resourceServer, String userId) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPermissionTicketByGranted(userId, resourceServerId);
return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findGranted(userId, resourceServerId),
(revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findGranted(resourceServer, userId),
(revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(PermissionTicket::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public List<PermissionTicket> findGranted(String resourceName, String userId, String resourceServerId) {
public List<PermissionTicket> findGranted(ResourceServer resourceServer, String resourceName, String userId) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPermissionTicketByResourceNameAndGranted(resourceName, userId, resourceServerId);
return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findGranted(resourceName, userId, resourceServerId),
(revision, permissions) -> new PermissionTicketResourceListQuery(revision, cacheKey, resourceName, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findGranted(resourceServer, resourceName, userId),
(revision, permissions) -> new PermissionTicketResourceListQuery(revision, cacheKey, resourceName, permissions.stream().map(PermissionTicket::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
@Override
public List<Resource> findGrantedResources(String requester, String name, int first, int max) {
public List<Resource> findGrantedResources(String requester, String name, Integer first, Integer max) {
return getPermissionTicketStoreDelegate().findGrantedResources(requester, name, first, max);
}
@Override
public List<Resource> findGrantedOwnerResources(String owner, int first, int max) {
return getPermissionTicketStoreDelegate().findGrantedOwnerResources(owner, first, max);
public List<Resource> findGrantedOwnerResources(String owner, Integer firstResult, Integer maxResults) {
return getPermissionTicketStoreDelegate().findGrantedOwnerResources(owner, firstResult, maxResults);
}
@Override
public List<PermissionTicket> findByOwner(String owner, String resourceServerId) {
public List<PermissionTicket> findByOwner(ResourceServer resourceServer, String owner) {
String resourceServerId = resourceServer == null ? null : resourceServer.getId();
String cacheKey = getPermissionTicketByOwner(owner, resourceServerId);
return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findByOwner(owner, resourceServerId),
(revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findByOwner(resourceServer, owner),
(revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(PermissionTicket::getId).collect(Collectors.toSet()), resourceServerId), resourceServer);
}
private <R, Q extends PermissionTicketQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId) {
private <R, Q extends PermissionTicketQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, ResourceServer resourceServer) {
Q query = cache.get(cacheKey, queryType);
if (query != null) {
logger.tracev("cache hit for key: {0}", cacheKey);
@ -1248,7 +1271,7 @@ public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
} else if (query.isInvalid(invalidations)) {
return resultSupplier.get();
} else {
return query.getPermissions().stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
return query.getPermissions().stream().map(resourceId -> (R) findById(resourceServer, resourceId)).collect(Collectors.toList());
}
}
}

View file

@ -56,7 +56,7 @@ public class CachedResource extends AbstractRevisioned implements InResourceServ
this.type = resource.getType();
this.owner = resource.getOwner();
this.iconUri = resource.getIconUri();
this.resourceServerId = resource.getResourceServer();
this.resourceServerId = resource.getResourceServer().getId();
ownerManagedAccess = resource.isOwnerManagedAccess();
this.uris = new DefaultLazyLoader<>(source -> new HashSet<>(source.getUris()), Collections::emptySet);

View file

@ -37,8 +37,10 @@ import org.keycloak.authorization.jpa.entities.PermissionTicketEntity;
import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PermissionTicketStore;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.common.util.Time;
import org.keycloak.models.utils.KeycloakModelUtils;
import javax.persistence.LockModeType;
@ -59,14 +61,14 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public long count(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId) {
public long count(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> querybuilder = builder.createQuery(Long.class);
Root<PermissionTicketEntity> root = querybuilder.from(PermissionTicketEntity.class);
querybuilder.select(root.get("id"));
List<Predicate> predicates = getPredicates(builder, root, resourceServerId, attributes);
List<Predicate> predicates = getPredicates(builder, root, resourceServer, attributes);
querybuilder.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(builder.asc(root.get("id")));
@ -77,12 +79,12 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
private List<Predicate> getPredicates(CriteriaBuilder builder,
Root<PermissionTicketEntity> root,
String resourceServerId,
ResourceServer resourceServer,
Map<PermissionTicket.FilterOption, String> attributes) {
List<Predicate> predicates = new ArrayList<>();
if (resourceServerId != null) {
predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServerId));
if (resourceServer != null) {
predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServer.getId()));
}
attributes.forEach((filterOption, value) -> {
@ -127,16 +129,16 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
public PermissionTicket create(ResourceServer resourceServer, Resource resource, Scope scope, String requester) {
PermissionTicketEntity entity = new PermissionTicketEntity();
entity.setId(KeycloakModelUtils.generateId());
entity.setResource(ResourceAdapter.toEntity(entityManager, provider.getStoreFactory().getResourceStore().findById(resourceId, resourceServer.getId())));
entity.setResource(ResourceAdapter.toEntity(entityManager, resource));
entity.setRequester(requester);
entity.setCreatedTimestamp(System.currentTimeMillis());
entity.setCreatedTimestamp(Time.currentTimeMillis());
if (scopeId != null) {
entity.setScope(ScopeAdapter.toEntity(entityManager, provider.getStoreFactory().getScopeStore().findById(scopeId, resourceServer.getId())));
if (scope != null) {
entity.setScope(ScopeAdapter.toEntity(entityManager, scope));
}
entity.setOwner(entity.getResource().getOwner());
@ -158,7 +160,7 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
@Override
public PermissionTicket findById(String id, String resourceServerId) {
public PermissionTicket findById(ResourceServer resourceServer, String id) {
if (id == null) {
return null;
}
@ -170,17 +172,17 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> findByResourceServer(final String resourceServerId) {
public List<PermissionTicket> findByResourceServer(final ResourceServer resourceServer) {
TypedQuery<String> query = entityManager.createNamedQuery("findPolicyIdByServerId", String.class);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
List<String> result = query.getResultList();
List<PermissionTicket> list = new LinkedList<>();
PermissionTicketStore ticketStore = provider.getStoreFactory().getPermissionTicketStore();
for (String id : result) {
PermissionTicket ticket = ticketStore.findById(id, resourceServerId);
PermissionTicket ticket = ticketStore.findById(resourceServer, id);
if (Objects.nonNull(ticket)) {
list.add(ticket);
}
@ -190,19 +192,19 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> findByResource(final String resourceId, String resourceServerId) {
public List<PermissionTicket> findByResource(ResourceServer resourceServer, final Resource resource) {
TypedQuery<String> query = entityManager.createNamedQuery("findPermissionIdByResource", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("resourceId", resourceId);
query.setParameter("serverId", resourceServerId);
query.setParameter("resourceId", resource.getId());
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
List<String> result = query.getResultList();
List<PermissionTicket> list = new LinkedList<>();
PermissionTicketStore ticketStore = provider.getStoreFactory().getPermissionTicketStore();
for (String id : result) {
PermissionTicket ticket = ticketStore.findById(id, resourceServerId);
PermissionTicket ticket = ticketStore.findById(resourceServer, id);
if (Objects.nonNull(ticket)) {
list.add(ticket);
}
@ -212,8 +214,8 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> findByScope(String scopeId, String resourceServerId) {
if (scopeId==null) {
public List<PermissionTicket> findByScope(ResourceServer resourceServer, Scope scope) {
if (scope == null) {
return Collections.emptyList();
}
@ -221,15 +223,15 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
TypedQuery<String> query = entityManager.createNamedQuery("findPermissionIdByScope", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("scopeId", scopeId);
query.setParameter("serverId", resourceServerId);
query.setParameter("scopeId", scope.getId());
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
List<String> result = query.getResultList();
List<PermissionTicket> list = new LinkedList<>();
PermissionTicketStore ticketStore = provider.getStoreFactory().getPermissionTicketStore();
for (String id : result) {
PermissionTicket ticket = ticketStore.findById(id, resourceServerId);
PermissionTicket ticket = ticketStore.findById(resourceServer, id);
if (Objects.nonNull(ticket)) {
list.add(ticket);
}
@ -239,14 +241,14 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> find(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId, int firstResult, int maxResult) {
public List<PermissionTicket> find(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes, Integer firstResult, Integer maxResult) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PermissionTicketEntity> querybuilder = builder.createQuery(PermissionTicketEntity.class);
Root<PermissionTicketEntity> root = querybuilder.from(PermissionTicketEntity.class);
querybuilder.select(root.get("id"));
List<Predicate> predicates = getPredicates(builder, root, resourceServerId, attributes);
List<Predicate> predicates = getPredicates(builder, root, resourceServer, attributes);
querybuilder.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(builder.asc(root.get("id")));
@ -257,7 +259,7 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
PermissionTicketStore ticketStore = provider.getStoreFactory().getPermissionTicketStore();
for (String id : result) {
PermissionTicket ticket = ticketStore.findById(id, resourceServerId);
PermissionTicket ticket = ticketStore.findById(resourceServer, id);
if (Objects.nonNull(ticket)) {
list.add(ticket);
}
@ -267,28 +269,28 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> findGranted(String userId, String resourceServerId) {
public List<PermissionTicket> findGranted(ResourceServer resourceServer, String userId) {
Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
filters.put(PermissionTicket.FilterOption.REQUESTER, userId);
return find(filters, resourceServerId, -1, -1);
return find(resourceServer, filters, null, null);
}
@Override
public List<PermissionTicket> findGranted(String resourceName, String userId, String resourceServerId) {
public List<PermissionTicket> findGranted(ResourceServer resourceServer, String resourceName, String userId) {
Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
filters.put(PermissionTicket.FilterOption.RESOURCE_NAME, resourceName);
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
filters.put(PermissionTicket.FilterOption.REQUESTER, userId);
return find(filters, resourceServerId, -1, -1);
return find(resourceServer, filters, null, null);
}
@Override
public List<Resource> findGrantedResources(String requester, String name, int first, int max) {
public List<Resource> findGrantedResources(String requester, String name, Integer first, Integer max) {
TypedQuery<String> query = name == null ?
entityManager.createNamedQuery("findGrantedResources", String.class) :
entityManager.createNamedQuery("findGrantedResourcesByName", String.class);
@ -305,7 +307,7 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
for (String id : result) {
Resource resource = resourceStore.findById(id, null);
Resource resource = resourceStore.findById(null, id);
if (Objects.nonNull(resource)) {
list.add(resource);
@ -316,18 +318,18 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<Resource> findGrantedOwnerResources(String owner, int first, int max) {
public List<Resource> findGrantedOwnerResources(String owner, Integer firstResult, Integer maxResults) {
TypedQuery<String> query = entityManager.createNamedQuery("findGrantedOwnerResources", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("owner", owner);
List<String> result = paginateQuery(query, first, max).getResultList();
List<String> result = paginateQuery(query, firstResult, maxResults).getResultList();
List<Resource> list = new LinkedList<>();
ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
for (String id : result) {
Resource resource = resourceStore.findById(id, null);
Resource resource = resourceStore.findById(null, id);
if (Objects.nonNull(resource)) {
list.add(resource);
@ -338,11 +340,11 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> findByOwner(String owner, String resourceServerId) {
public List<PermissionTicket> findByOwner(ResourceServer resourceServer, String owner) {
TypedQuery<String> query = entityManager.createNamedQuery("findPolicyIdByType", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
query.setParameter("owner", owner);
List<String> result = query.getResultList();
@ -350,7 +352,7 @@ public class JPAPermissionTicketStore implements PermissionTicketStore {
PermissionTicketStore ticketStore = provider.getStoreFactory().getPermissionTicketStore();
for (String id : result) {
PermissionTicket ticket = ticketStore.findById(id, resourceServerId);
PermissionTicket ticket = ticketStore.findById(resourceServer, id);
if (Objects.nonNull(ticket)) {
list.add(ticket);
}

View file

@ -24,6 +24,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
@ -37,7 +38,9 @@ import javax.persistence.criteria.Root;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.jpa.entities.PolicyEntity;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PolicyStore;
import org.keycloak.authorization.store.StoreFactory;
import org.keycloak.models.utils.KeycloakModelUtils;
@ -60,7 +63,7 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
public Policy create(ResourceServer resourceServer, AbstractPolicyRepresentation representation) {
PolicyEntity entity = new PolicyEntity();
if (representation.getId() == null) {
@ -89,7 +92,7 @@ public class JPAPolicyStore implements PolicyStore {
@Override
public Policy findById(String id, String resourceServerId) {
public Policy findById(ResourceServer resourceServer, String id) {
if (id == null) {
return null;
}
@ -104,11 +107,11 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public Policy findByName(String name, String resourceServerId) {
public Policy findByName(ResourceServer resourceServer, String name) {
TypedQuery<PolicyEntity> query = entityManager.createNamedQuery("findPolicyIdByName", PolicyEntity.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer.getId());
query.setParameter("name", name);
try {
@ -119,15 +122,15 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public List<Policy> findByResourceServer(final String resourceServerId) {
public List<Policy> findByResourceServer(final ResourceServer resourceServer) {
TypedQuery<String> query = entityManager.createNamedQuery("findPolicyIdByServerId", String.class);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer.getId());
List<String> result = query.getResultList();
List<Policy> list = new LinkedList<>();
for (String id : result) {
Policy policy = provider.getStoreFactory().getPolicyStore().findById(id, resourceServerId);
Policy policy = provider.getStoreFactory().getPolicyStore().findById(resourceServer, id);
if (Objects.nonNull(policy)) {
list.add(policy);
}
@ -136,15 +139,15 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public List<Policy> findByResourceServer(Map<Policy.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
public List<Policy> findByResourceServer(ResourceServer resourceServer, Map<Policy.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PolicyEntity> querybuilder = builder.createQuery(PolicyEntity.class);
Root<PolicyEntity> root = querybuilder.from(PolicyEntity.class);
List<Predicate> predicates = new ArrayList();
querybuilder.select(root.get("id"));
if (resourceServerId != null) {
predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServerId));
if (resourceServer != null) {
predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServer.getId()));
}
attributes.forEach((filterOption, value) -> {
@ -193,10 +196,10 @@ public class JPAPolicyStore implements PolicyStore {
TypedQuery query = entityManager.createQuery(querybuilder);
List<String> result = paginateQuery(query, firstResult, maxResult).getResultList();
List<String> result = paginateQuery(query, firstResult, maxResults).getResultList();
List<Policy> list = new LinkedList<>();
for (String id : result) {
Policy policy = provider.getStoreFactory().getPolicyStore().findById(id, resourceServerId);
Policy policy = provider.getStoreFactory().getPolicyStore().findById(resourceServer, id);
if (Objects.nonNull(policy)) {
list.add(policy);
}
@ -205,28 +208,28 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
public void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer) {
TypedQuery<PolicyEntity> query = entityManager.createNamedQuery("findPolicyIdByResource", PolicyEntity.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("resourceId", resourceId);
query.setParameter("serverId", resourceServerId);
query.setParameter("resourceId", resource.getId());
query.setParameter("serverId", resourceServer.getId());
PolicyStore storeFactory = provider.getStoreFactory().getPolicyStore();
closing(query.getResultStream()
.map(entity -> storeFactory.findById(entity.getId(), resourceServerId))
.map(entity -> storeFactory.findById(resourceServer, entity.getId()))
.filter(Objects::nonNull))
.forEach(consumer::accept);
}
@Override
public void findByResourceType(String resourceType, String resourceServerId, Consumer<Policy> consumer) {
public void findByResourceType(ResourceServer resourceServer, String resourceType, Consumer<Policy> consumer) {
TypedQuery<PolicyEntity> query = entityManager.createNamedQuery("findPolicyIdByResourceType", PolicyEntity.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("type", resourceType);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer.getId());
closing(query.getResultStream()
.map(id -> new PolicyAdapter(id, entityManager, provider.getStoreFactory()))
@ -235,8 +238,8 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
if (scopeIds==null || scopeIds.isEmpty()) {
public List<Policy> findByScopes(ResourceServer resourceServer, List<Scope> scopes) {
if (scopes==null || scopes.isEmpty()) {
return Collections.emptyList();
}
@ -244,34 +247,34 @@ public class JPAPolicyStore implements PolicyStore {
TypedQuery<PolicyEntity> query = entityManager.createNamedQuery("findPolicyIdByScope", PolicyEntity.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("scopeIds", scopeIds);
query.setParameter("serverId", resourceServerId);
query.setParameter("scopeIds", scopes.stream().map(Scope::getId).collect(Collectors.toSet()));
query.setParameter("serverId", resourceServer.getId());
List<Policy> list = new LinkedList<>();
PolicyStore storeFactory = provider.getStoreFactory().getPolicyStore();
for (PolicyEntity entity : query.getResultList()) {
list.add(storeFactory.findById(entity.getId(), resourceServerId));
list.add(storeFactory.findById(resourceServer, entity.getId()));
}
return list;
}
@Override
public void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer) {
public void findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes, Consumer<Policy> consumer) {
// Use separate subquery to handle DB2 and MSSSQL
TypedQuery<PolicyEntity> query;
if (resourceId == null) {
if (resource == null) {
query = entityManager.createNamedQuery("findPolicyIdByNullResourceScope", PolicyEntity.class);
} else {
query = entityManager.createNamedQuery("findPolicyIdByResourceScope", PolicyEntity.class);
query.setParameter("resourceId", resourceId);
query.setParameter("resourceId", resource.getId());
}
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("scopeIds", scopeIds);
query.setParameter("serverId", resourceServerId);
query.setParameter("scopeIds", scopes.stream().map(Scope::getId).collect(Collectors.toSet()));
query.setParameter("serverId", resourceServer.getId());
StoreFactory storeFactory = provider.getStoreFactory();
@ -282,17 +285,17 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public List<Policy> findByType(String type, String resourceServerId) {
public List<Policy> findByType(ResourceServer resourceServer, String type) {
TypedQuery<String> query = entityManager.createNamedQuery("findPolicyIdByType", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer.getId());
query.setParameter("type", type);
List<String> result = query.getResultList();
List<Policy> list = new LinkedList<>();
for (String id : result) {
Policy policy = provider.getStoreFactory().getPolicyStore().findById(id, resourceServerId);
Policy policy = provider.getStoreFactory().getPolicyStore().findById(resourceServer, id);
if (Objects.nonNull(policy)) {
list.add(policy);
}
@ -301,18 +304,18 @@ public class JPAPolicyStore implements PolicyStore {
}
@Override
public List<Policy> findDependentPolicies(String policyId, String resourceServerId) {
public List<Policy> findDependentPolicies(ResourceServer resourceServer, String policyId) {
TypedQuery<String> query = entityManager.createNamedQuery("findPolicyIdByDependentPolices", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer.getId());
query.setParameter("policyId", policyId);
List<String> result = query.getResultList();
List<Policy> list = new LinkedList<>();
for (String id : result) {
Policy policy = provider.getStoreFactory().getPolicyStore().findById(id, resourceServerId);
Policy policy = provider.getStoreFactory().getPolicyStore().findById(resourceServer, id);
if (Objects.nonNull(policy)) {
list.add(policy);
}

View file

@ -21,6 +21,7 @@ import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.jpa.entities.ResourceEntity;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.authorization.store.StoreFactory;
import org.keycloak.models.utils.KeycloakModelUtils;
@ -38,7 +39,9 @@ import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.keycloak.models.jpa.PaginationUtils.paginateQuery;
import static org.keycloak.utils.StreamsUtil.closing;
@ -57,7 +60,7 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public Resource create(String id, String name, ResourceServer resourceServer, String owner) {
public Resource create(ResourceServer resourceServer, String id, String name, String owner) {
ResourceEntity entity = new ResourceEntity();
if (id == null) {
@ -86,7 +89,7 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public Resource findById(String id, String resourceServerId) {
public Resource findById(ResourceServer resourceServer, String id) {
if (id == null) {
return null;
}
@ -97,24 +100,24 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer) {
findByOwnerFilter(ownerId, resourceServerId, consumer, -1, -1);
public void findByOwner(ResourceServer resourceServer, String ownerId, Consumer<Resource> consumer) {
findByOwnerFilter(ownerId, resourceServer, consumer, -1, -1);
}
@Override
public List<Resource> findByOwner(String ownerId, String resourceServerId, int first, int max) {
public List<Resource> findByOwner(ResourceServer resourceServer, String ownerId, Integer firstResult, Integer maxResults) {
List<Resource> list = new LinkedList<>();
findByOwnerFilter(ownerId, resourceServerId, list::add, first, max);
findByOwnerFilter(ownerId, resourceServer, list::add, firstResult, maxResults);
return list;
}
private void findByOwnerFilter(String ownerId, String resourceServerId, Consumer<Resource> consumer, int firstResult, int maxResult) {
private void findByOwnerFilter(String ownerId, ResourceServer resourceServer, Consumer<Resource> consumer, int firstResult, int maxResult) {
boolean pagination = firstResult > -1 && maxResult > -1;
String queryName = pagination ? "findResourceIdByOwnerOrdered" : "findResourceIdByOwner";
if (resourceServerId == null) {
if (resourceServer == null) {
queryName = pagination ? "findAnyResourceIdByOwnerOrdered" : "findAnyResourceIdByOwner";
}
@ -123,8 +126,8 @@ public class JPAResourceStore implements ResourceStore {
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("owner", ownerId);
if (resourceServerId != null) {
query.setParameter("serverId", resourceServerId);
if (resourceServer != null) {
query.setParameter("serverId", resourceServer.getId());
}
if (pagination) {
@ -133,23 +136,23 @@ public class JPAResourceStore implements ResourceStore {
}
ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
closing(query.getResultStream().map(id -> resourceStore.findById(id.getId(), resourceServerId))).forEach(consumer);
closing(query.getResultStream().map(id -> resourceStore.findById(resourceServer, id.getId()))).forEach(consumer);
}
@Override
public List<Resource> findByUri(String uri, String resourceServerId) {
public List<Resource> findByUri(ResourceServer resourceServer, String uri) {
TypedQuery<String> query = entityManager.createNamedQuery("findResourceIdByUri", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("uri", uri);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
List<String> result = query.getResultList();
List<Resource> list = new LinkedList<>();
ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
for (String id : result) {
Resource resource = resourceStore.findById(id, resourceServerId);
Resource resource = resourceStore.findById(resourceServer, id);
if (resource != null) {
list.add(resource);
@ -160,17 +163,17 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public List<Resource> findByResourceServer(String resourceServerId) {
public List<Resource> findByResourceServer(ResourceServer resourceServer) {
TypedQuery<String> query = entityManager.createNamedQuery("findResourceIdByServerId", String.class);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
List<String> result = query.getResultList();
List<Resource> list = new LinkedList<>();
ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
for (String id : result) {
Resource resource = resourceStore.findById(id, resourceServerId);
Resource resource = resourceStore.findById(resourceServer, id);
if (resource != null) {
list.add(resource);
@ -181,15 +184,15 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public List<Resource> findByResourceServer(Map<Resource.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
public List<Resource> findByResourceServer(ResourceServer resourceServer, Map<Resource.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<ResourceEntity> querybuilder = builder.createQuery(ResourceEntity.class);
Root<ResourceEntity> root = querybuilder.from(ResourceEntity.class);
querybuilder.select(root.get("id"));
List<Predicate> predicates = new ArrayList();
if (resourceServerId != null) {
predicates.add(builder.equal(root.get("resourceServer"), resourceServerId));
if (resourceServer != null) {
predicates.add(builder.equal(root.get("resourceServer"), resourceServer.getId()));
}
attributes.forEach((filterOption, value) -> {
@ -229,12 +232,12 @@ public class JPAResourceStore implements ResourceStore {
TypedQuery query = entityManager.createQuery(querybuilder);
List<String> result = paginateQuery(query, firstResult, maxResult).getResultList();
List<String> result = paginateQuery(query, firstResult, maxResults).getResultList();
List<Resource> list = new LinkedList<>();
ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
for (String id : result) {
Resource resource = resourceStore.findById(id, resourceServerId);
Resource resource = resourceStore.findById(resourceServer, id);
if (resource != null) {
list.add(resource);
@ -245,12 +248,12 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public void findByScope(List<String> scopes, String resourceServerId, Consumer<Resource> consumer) {
public void findByScopes(ResourceServer resourceServer, Set<Scope> scopes, Consumer<Resource> consumer) {
TypedQuery<ResourceEntity> query = entityManager.createNamedQuery("findResourceIdByScope", ResourceEntity.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("scopeIds", scopes);
query.setParameter("serverId", resourceServerId);
query.setParameter("scopeIds", scopes.stream().map(Scope::getId).collect(Collectors.toSet()));
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
StoreFactory storeFactory = provider.getStoreFactory();
@ -260,15 +263,10 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public Resource findByName(String name, String resourceServerId) {
return findByName(name, resourceServerId, resourceServerId);
}
@Override
public Resource findByName(String name, String ownerId, String resourceServerId) {
public Resource findByName(ResourceServer resourceServer, String name, String ownerId) {
TypedQuery<ResourceEntity> query = entityManager.createNamedQuery("findResourceIdByName", ResourceEntity.class);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
query.setParameter("name", name);
query.setParameter("ownerId", ownerId);
@ -280,12 +278,12 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public void findByType(String type, String resourceServerId, Consumer<Resource> consumer) {
findByType(type, resourceServerId, resourceServerId, consumer);
public void findByType(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
findByType(resourceServer, type, resourceServer == null ? null : resourceServer.getId(), consumer);
}
@Override
public void findByType(String type, String owner, String resourceServerId, Consumer<Resource> consumer) {
public void findByType(ResourceServer resourceServer, String type, String owner, Consumer<Resource> consumer) {
TypedQuery<ResourceEntity> query;
if (owner != null) {
@ -301,7 +299,7 @@ public class JPAResourceStore implements ResourceStore {
query.setParameter("ownerId", owner);
}
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
StoreFactory storeFactory = provider.getStoreFactory();
@ -311,12 +309,12 @@ public class JPAResourceStore implements ResourceStore {
}
@Override
public void findByTypeInstance(String type, String resourceServerId, Consumer<Resource> consumer) {
public void findByTypeInstance(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
TypedQuery<ResourceEntity> query = entityManager.createNamedQuery("findResourceIdByTypeInstance", ResourceEntity.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("type", type);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer == null ? null : resourceServer.getId());
StoreFactory storeFactory = provider.getStoreFactory();

View file

@ -55,12 +55,12 @@ public class JPAScopeStore implements ScopeStore {
}
@Override
public Scope create(final String name, final ResourceServer resourceServer) {
return create(null, name, resourceServer);
public Scope create(final ResourceServer resourceServer, final String name) {
return create(resourceServer, null, name);
}
@Override
public Scope create(String id, final String name, final ResourceServer resourceServer) {
public Scope create(final ResourceServer resourceServer, String id, final String name) {
ScopeEntity entity = new ScopeEntity();
if (id == null) {
@ -88,7 +88,7 @@ public class JPAScopeStore implements ScopeStore {
}
@Override
public Scope findById(String id, String resourceServerId) {
public Scope findById(ResourceServer resourceServer, String id) {
if (id == null) {
return null;
}
@ -100,45 +100,45 @@ public class JPAScopeStore implements ScopeStore {
}
@Override
public Scope findByName(String name, String resourceServerId) {
public Scope findByName(ResourceServer resourceServer, String name) {
try {
TypedQuery<String> query = entityManager.createNamedQuery("findScopeIdByName", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("serverId", resourceServerId);
query.setParameter("serverId", resourceServer.getId());
query.setParameter("name", name);
String id = query.getSingleResult();
return provider.getStoreFactory().getScopeStore().findById(id, resourceServerId);
return provider.getStoreFactory().getScopeStore().findById(resourceServer, id);
} catch (NoResultException nre) {
return null;
}
}
@Override
public List<Scope> findByResourceServer(final String serverId) {
public List<Scope> findByResourceServer(final ResourceServer resourceServer) {
TypedQuery<String> query = entityManager.createNamedQuery("findScopeIdByResourceServer", String.class);
query.setFlushMode(FlushModeType.COMMIT);
query.setParameter("serverId", serverId);
query.setParameter("serverId", resourceServer.getId());
List<String> result = query.getResultList();
List<Scope> list = new LinkedList<>();
for (String id : result) {
list.add(provider.getStoreFactory().getScopeStore().findById(id, serverId));
list.add(provider.getStoreFactory().getScopeStore().findById(resourceServer, id));
}
return list;
}
@Override
public List<Scope> findByResourceServer(Map<Scope.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
public List<Scope> findByResourceServer(ResourceServer resourceServer, Map<Scope.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<ScopeEntity> querybuilder = builder.createQuery(ScopeEntity.class);
Root<ScopeEntity> root = querybuilder.from(ScopeEntity.class);
querybuilder.select(root.get("id"));
List<Predicate> predicates = new ArrayList();
predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServerId));
predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServer.getId()));
attributes.forEach((filterOption, value) -> {
switch (filterOption) {
@ -157,10 +157,10 @@ public class JPAScopeStore implements ScopeStore {
TypedQuery query = entityManager.createQuery(querybuilder);
List result = paginateQuery(query, firstResult, maxResult).getResultList();
List result = paginateQuery(query, firstResult, maxResults).getResultList();
List<Scope> list = new LinkedList<>();
for (Object id : result) {
list.add(provider.getStoreFactory().getScopeStore().findById((String)id, resourceServerId));
list.add(provider.getStoreFactory().getScopeStore().findById(resourceServer, (String)id));
}
return list;

View file

@ -20,6 +20,7 @@ import static org.keycloak.authorization.UserManagedPermissionUtil.updatePolicy;
import javax.persistence.EntityManager;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.jpa.entities.PermissionTicketEntity;
import org.keycloak.authorization.jpa.entities.PolicyEntity;
import org.keycloak.authorization.jpa.entities.ScopeEntity;
@ -101,7 +102,8 @@ public class PermissionTicketAdapter implements PermissionTicket, JpaModel<Permi
return null;
}
return storeFactory.getPolicyStore().findById(policy.getId(), entity.getResourceServer().getId());
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(entity.getResourceServer().getId());
return storeFactory.getPolicyStore().findById(resourceServer, policy.getId());
}
@Override
@ -113,7 +115,7 @@ public class PermissionTicketAdapter implements PermissionTicket, JpaModel<Permi
@Override
public Resource getResource() {
return storeFactory.getResourceStore().findById(entity.getResource().getId(), getResourceServer().getId());
return storeFactory.getResourceStore().findById(getResourceServer(), entity.getResource().getId());
}
@Override
@ -124,7 +126,7 @@ public class PermissionTicketAdapter implements PermissionTicket, JpaModel<Permi
return null;
}
return storeFactory.getScopeStore().findById(scope.getId(), getResourceServer().getId());
return storeFactory.getScopeStore().findById(getResourceServer(), scope.getId());
}
@Override

View file

@ -168,8 +168,9 @@ public class PolicyAdapter extends AbstractAuthorizationModel implements Policy,
@Override
public Set<Resource> getResources() {
Set<Resource> set = new HashSet<>();
ResourceServer resourceServer = getResourceServer();
for (ResourceEntity res : entity.getResources()) {
set.add(storeFactory.getResourceStore().findById(res.getId(), entity.getResourceServer().getId()));
set.add(storeFactory.getResourceStore().findById(resourceServer, res.getId()));
}
return Collections.unmodifiableSet(set);
}
@ -177,8 +178,9 @@ public class PolicyAdapter extends AbstractAuthorizationModel implements Policy,
@Override
public Set<Scope> getScopes() {
Set<Scope> set = new HashSet<>();
ResourceServer resourceServer = getResourceServer();
for (ScopeEntity res : entity.getScopes()) {
set.add(storeFactory.getScopeStore().findById(res.getId(), entity.getResourceServer().getId()));
set.add(storeFactory.getScopeStore().findById(resourceServer, res.getId()));
}
return Collections.unmodifiableSet(set);
}

View file

@ -116,8 +116,9 @@ public class ResourceAdapter extends AbstractAuthorizationModel implements Resou
@Override
public List<Scope> getScopes() {
List<Scope> scopes = new LinkedList<>();
ResourceServer resourceServer = getResourceServer();
for (ScopeEntity scope : entity.getScopes()) {
scopes.add(storeFactory.getScopeStore().findById(scope.getId(), entity.getResourceServer()));
scopes.add(storeFactory.getScopeStore().findById(resourceServer, scope.getId()));
}
return Collections.unmodifiableList(scopes);
@ -136,8 +137,8 @@ public class ResourceAdapter extends AbstractAuthorizationModel implements Resou
}
@Override
public String getResourceServer() {
return entity.getResourceServer();
public ResourceServer getResourceServer() {
return storeFactory.getResourceServerStore().findById(entity.getResourceServer());
}
@Override

View file

@ -24,8 +24,11 @@ import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.PermissionTicket.SearchableFields;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PermissionTicketStore;
import org.keycloak.authorization.store.ResourceServerStore;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.common.util.Time;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.map.authorization.adapter.MapPermissionTicketAdapter;
@ -69,18 +72,18 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
return new MapPermissionTicketAdapter(origEntity, authorizationProvider.getStoreFactory());
}
private DefaultModelCriteria<PermissionTicket> forResourceServer(String resourceServerId) {
private DefaultModelCriteria<PermissionTicket> forResourceServer(ResourceServer resourceServer) {
DefaultModelCriteria<PermissionTicket> mcb = criteria();
return resourceServerId == null
return resourceServer == null
? mcb
: mcb.compare(SearchableFields.RESOURCE_SERVER_ID, Operator.EQ,
resourceServerId);
resourceServer.getId());
}
@Override
public long count(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId) {
DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServerId).and(
public long count(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes) {
DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServer).and(
attributes.entrySet().stream()
.map(this::filterEntryToDefaultModelCriteria)
.toArray(DefaultModelCriteria[]::new)
@ -90,33 +93,33 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
}
@Override
public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
LOG.tracef("create(%s, %s, %s, %s)%s", resourceId, scopeId, requester, resourceServer, getShortStackTrace());
public PermissionTicket create(ResourceServer resourceServer, Resource resource, Scope scope, String requester) {
LOG.tracef("create(%s, %s, %s, %s)%s", resource, scope, requester, resourceServer, getShortStackTrace());
String owner = authorizationProvider.getStoreFactory().getResourceStore().findById(resourceId, resourceServer.getId()).getOwner();
String owner = authorizationProvider.getStoreFactory().getResourceStore().findById(resourceServer, resource.getId()).getOwner();
// @UniqueConstraint(columnNames = {"OWNER", "REQUESTER", "RESOURCE_SERVER_ID", "RESOURCE_ID", "SCOPE_ID"})
DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServer.getId())
DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServer)
.compare(SearchableFields.OWNER, Operator.EQ, owner)
.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resourceId)
.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resource)
.compare(SearchableFields.REQUESTER, Operator.EQ, requester);
if (scopeId != null) {
mcb = mcb.compare(SearchableFields.SCOPE_ID, Operator.EQ, scopeId);
if (scope != null) {
mcb = mcb.compare(SearchableFields.SCOPE_ID, Operator.EQ, scope.getId());
}
if (tx.getCount(withCriteria(mcb)) > 0) {
throw new ModelDuplicateException("Permission ticket for resource server: '" + resourceServer.getId()
+ ", Resource: " + resourceId + ", owner: " + owner + ", scopeId: " + scopeId + " already exists.");
+ ", Resource: " + resource + ", owner: " + owner + ", scopeId: " + scope + " already exists.");
}
MapPermissionTicketEntity entity = new MapPermissionTicketEntityImpl();
entity.setResourceId(resourceId);
entity.setResourceId(resource.getId());
entity.setRequester(requester);
entity.setCreatedTimestamp(System.currentTimeMillis());
entity.setCreatedTimestamp(Time.currentTimeMillis());
if (scopeId != null) {
entity.setScopeId(scopeId);
if (scope != null) {
entity.setScopeId(scope.getId());
}
entity.setOwner(owner);
@ -131,7 +134,7 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
public void delete(String id) {
LOG.tracef("delete(%s)%s", id, getShortStackTrace());
PermissionTicket permissionTicket = findById(id, null);
PermissionTicket permissionTicket = findById((ResourceServer) null, id);
if (permissionTicket == null) return;
tx.delete(id);
@ -139,10 +142,10 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
}
@Override
public PermissionTicket findById(String id, String resourceServerId) {
LOG.tracef("findById(%s, %s)%s", id, resourceServerId, getShortStackTrace());
public PermissionTicket findById(ResourceServer resourceServer, String id) {
LOG.tracef("findById(%s, %s)%s", id, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.ID, Operator.EQ, id)))
.findFirst()
.map(this::entityToAdapter)
@ -150,47 +153,47 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> findByResourceServer(String resourceServerId) {
LOG.tracef("findByResourceServer(%s)%s", resourceServerId, getShortStackTrace());
public List<PermissionTicket> findByResourceServer(ResourceServer resourceServer) {
LOG.tracef("findByResourceServer(%s)%s", resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)))
return tx.read(withCriteria(forResourceServer(resourceServer)))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<PermissionTicket> findByOwner(String owner, String resourceServerId) {
LOG.tracef("findByOwner(%s, %s)%s", owner, resourceServerId, getShortStackTrace());
public List<PermissionTicket> findByOwner(ResourceServer resourceServer, String owner) {
LOG.tracef("findByOwner(%s, %s)%s", owner, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.OWNER, Operator.EQ, owner)))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<PermissionTicket> findByResource(String resourceId, String resourceServerId) {
LOG.tracef("findByResource(%s, %s)%s", resourceId, resourceServerId, getShortStackTrace());
public List<PermissionTicket> findByResource(ResourceServer resourceServer, Resource resource) {
LOG.tracef("findByResource(%s, %s)%s", resource, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resourceId)))
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resource.getId())))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<PermissionTicket> findByScope(String scopeId, String resourceServerId) {
LOG.tracef("findByScope(%s, %s)%s", scopeId, resourceServerId, getShortStackTrace());
public List<PermissionTicket> findByScope(ResourceServer resourceServer, Scope scope) {
LOG.tracef("findByScope(%s, %s)%s", scope, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
.compare(SearchableFields.SCOPE_ID, Operator.EQ, scopeId)))
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.SCOPE_ID, Operator.EQ, scope.getId())))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<PermissionTicket> find(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId, int firstResult, int maxResult) {
DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServerId);
public List<PermissionTicket> find(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes, Integer firstResult, Integer maxResult) {
DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServer);
if (attributes.containsKey(PermissionTicket.FilterOption.RESOURCE_NAME)) {
String expectedResourceName = attributes.remove(PermissionTicket.FilterOption.RESOURCE_NAME);
@ -199,7 +202,7 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
filterOptionStringMap.put(Resource.FilterOption.EXACT_NAME, new String[]{expectedResourceName});
List<Resource> r = authorizationProvider.getStoreFactory().getResourceStore().findByResourceServer(filterOptionStringMap, resourceServerId, -1, -1);
List<Resource> r = authorizationProvider.getStoreFactory().getResourceStore().findByResourceServer(resourceServer, filterOptionStringMap, null, null);
if (r == null || r.isEmpty()) {
return Collections.emptyList();
}
@ -248,28 +251,28 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<PermissionTicket> findGranted(String userId, String resourceServerId) {
public List<PermissionTicket> findGranted(ResourceServer resourceServer, String userId) {
Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
filters.put(PermissionTicket.FilterOption.REQUESTER, userId);
return find(filters, resourceServerId, -1, -1);
return find(resourceServer, filters, null, null);
}
@Override
public List<PermissionTicket> findGranted(String resourceName, String userId, String resourceServerId) {
public List<PermissionTicket> findGranted(ResourceServer resourceServer, String resourceName, String userId) {
Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
filters.put(PermissionTicket.FilterOption.RESOURCE_NAME, resourceName);
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
filters.put(PermissionTicket.FilterOption.REQUESTER, userId);
return find(filters, resourceServerId, -1, -1);
return find(resourceServer, filters, null, null);
}
@Override
public List<Resource> findGrantedResources(String requester, String name, int first, int max) {
public List<Resource> findGrantedResources(String requester, String name, Integer first, Integer max) {
DefaultModelCriteria<PermissionTicket> mcb = criteria();
mcb = mcb.compare(SearchableFields.REQUESTER, Operator.EQ, requester)
.compare(SearchableFields.GRANTED_TIMESTAMP, Operator.EXISTS);
@ -277,6 +280,7 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
Function<MapPermissionTicketEntity, Resource> ticketResourceMapper;
ResourceStore resourceStore = authorizationProvider.getStoreFactory().getResourceStore();
ResourceServerStore resourceServerStore = authorizationProvider.getStoreFactory().getResourceServerStore();
if (name != null) {
ticketResourceMapper = ticket -> {
Map<Resource.FilterOption, String[]> filterOptionMap = new EnumMap<>(Resource.FilterOption.class);
@ -284,13 +288,13 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
filterOptionMap.put(Resource.FilterOption.ID, new String[] {ticket.getResourceId()});
filterOptionMap.put(Resource.FilterOption.NAME, new String[] {name});
List<Resource> resource = resourceStore.findByResourceServer(filterOptionMap, ticket.getResourceServerId(), -1, 1);
List<Resource> resource = resourceStore.findByResourceServer(resourceServerStore.findById(ticket.getResourceServerId()), filterOptionMap, -1, 1);
return resource.isEmpty() ? null : resource.get(0);
};
} else {
ticketResourceMapper = ticket -> resourceStore
.findById(ticket.getResourceId(), ticket.getResourceServerId());
.findById(resourceServerStore.findById(ticket.getResourceServerId()), ticket.getResourceId());
}
return paginatedStream(tx.read(withCriteria(mcb).orderBy(SearchableFields.RESOURCE_ID, ASCENDING))
@ -301,14 +305,16 @@ public class MapPermissionTicketStore implements PermissionTicketStore {
}
@Override
public List<Resource> findGrantedOwnerResources(String owner, int first, int max) {
public List<Resource> findGrantedOwnerResources(String owner, Integer firstResult, Integer maxResults) {
DefaultModelCriteria<PermissionTicket> mcb = criteria();
mcb = mcb.compare(SearchableFields.OWNER, Operator.EQ, owner);
ResourceStore resourceStore = authorizationProvider.getStoreFactory().getResourceStore();
ResourceServerStore resourceServerStore = authorizationProvider.getStoreFactory().getResourceServerStore();
return paginatedStream(tx.read(withCriteria(mcb).orderBy(SearchableFields.RESOURCE_ID, ASCENDING))
.filter(distinctByKey(MapPermissionTicketEntity::getResourceId)), first, max)
.map(ticket -> authorizationProvider.getStoreFactory().getResourceStore()
.findById(ticket.getResourceId(), ticket.getResourceServerId()))
.filter(distinctByKey(MapPermissionTicketEntity::getResourceId)), firstResult, maxResults)
.map(ticket -> resourceStore.findById(resourceServerStore.findById(ticket.getResourceServerId()), ticket.getResourceId()))
.collect(Collectors.toList());
}
}

View file

@ -21,7 +21,9 @@ import org.jboss.logging.Logger;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Policy.SearchableFields;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PolicyStore;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
@ -63,21 +65,21 @@ public class MapPolicyStore implements PolicyStore {
return new MapPolicyAdapter(origEntity, authorizationProvider.getStoreFactory());
}
private DefaultModelCriteria<Policy> forResourceServer(String resourceServerId) {
private DefaultModelCriteria<Policy> forResourceServer(ResourceServer resourceServer) {
DefaultModelCriteria<Policy> mcb = criteria();
return resourceServerId == null
return resourceServer == null
? mcb
: mcb.compare(SearchableFields.RESOURCE_SERVER_ID, Operator.EQ,
resourceServerId);
resourceServer.getId());
}
@Override
public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
public Policy create(ResourceServer resourceServer, AbstractPolicyRepresentation representation) {
LOG.tracef("create(%s, %s, %s)%s", representation.getId(), resourceServer.getId(), resourceServer, getShortStackTrace());
// @UniqueConstraint(columnNames = {"NAME", "RESOURCE_SERVER_ID"})
DefaultModelCriteria<Policy> mcb = forResourceServer(resourceServer.getId())
DefaultModelCriteria<Policy> mcb = forResourceServer(resourceServer)
.compare(SearchableFields.NAME, Operator.EQ, representation.getName());
if (tx.getCount(withCriteria(mcb)) > 0) {
@ -103,10 +105,10 @@ public class MapPolicyStore implements PolicyStore {
}
@Override
public Policy findById(String id, String resourceServerId) {
LOG.tracef("findById(%s, %s)%s", id, resourceServerId, getShortStackTrace());
public Policy findById(ResourceServer resourceServer, String id) {
LOG.tracef("findById(%s, %s)%s", id, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.ID, Operator.EQ, id)))
.findFirst()
.map(this::entityToAdapter)
@ -114,10 +116,10 @@ public class MapPolicyStore implements PolicyStore {
}
@Override
public Policy findByName(String name, String resourceServerId) {
LOG.tracef("findByName(%s, %s)%s", name, resourceServerId, getShortStackTrace());
public Policy findByName(ResourceServer resourceServer, String name) {
LOG.tracef("findByName(%s, %s)%s", name, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.NAME, Operator.EQ, name)))
.findFirst()
.map(this::entityToAdapter)
@ -125,19 +127,19 @@ public class MapPolicyStore implements PolicyStore {
}
@Override
public List<Policy> findByResourceServer(String id) {
LOG.tracef("findByResourceServer(%s)%s", id, getShortStackTrace());
public List<Policy> findByResourceServer(ResourceServer resourceServer) {
LOG.tracef("findByResourceServer(%s)%s", resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(id)))
return tx.read(withCriteria(forResourceServer(resourceServer)))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<Policy> findByResourceServer(Map<Policy.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
LOG.tracef("findByResourceServer(%s, %s, %d, %d)%s", attributes, resourceServerId, firstResult, maxResult, getShortStackTrace());
public List<Policy> findByResourceServer(ResourceServer resourceServer, Map<Policy.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
LOG.tracef("findByResourceServer(%s, %s, %d, %d)%s", attributes, resourceServer, firstResult, maxResults, getShortStackTrace());
DefaultModelCriteria<Policy> mcb = forResourceServer(resourceServerId).and(
DefaultModelCriteria<Policy> mcb = forResourceServer(resourceServer).and(
attributes.entrySet().stream()
.map(this::filterEntryToDefaultModelCriteria)
.filter(Objects::nonNull)
@ -148,10 +150,10 @@ public class MapPolicyStore implements PolicyStore {
mcb = mcb.compare(SearchableFields.OWNER, Operator.NOT_EXISTS);
}
return tx.read(withCriteria(mcb).pagination(firstResult, maxResult, SearchableFields.NAME))
return tx.read(withCriteria(mcb).pagination(firstResult, maxResults, SearchableFields.NAME))
.map(MapPolicyEntity::getId)
// We need to go through cache
.map(id -> authorizationProvider.getStoreFactory().getPolicyStore().findById(id, resourceServerId))
.map(id -> authorizationProvider.getStoreFactory().getPolicyStore().findById(resourceServer, id))
.collect(Collectors.toList());
}
@ -194,39 +196,39 @@ public class MapPolicyStore implements PolicyStore {
}
@Override
public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
LOG.tracef("findByResource(%s, %s, %s)%s", resourceId, resourceServerId, consumer, getShortStackTrace());
public void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer) {
LOG.tracef("findByResource(%s, %s, %s)%s", resourceServer, resource, consumer, getShortStackTrace());
tx.read(withCriteria(forResourceServer(resourceServerId)
.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resourceId)))
tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resource.getId())))
.map(this::entityToAdapter)
.forEach(consumer);
}
@Override
public void findByResourceType(String type, String resourceServerId, Consumer<Policy> policyConsumer) {
tx.read(withCriteria(forResourceServer(resourceServerId)
public void findByResourceType(ResourceServer resourceServer, String type, Consumer<Policy> policyConsumer) {
tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.CONFIG, Operator.LIKE, (Object[]) new String[]{"defaultResourceType", type})))
.map(this::entityToAdapter)
.forEach(policyConsumer);
}
@Override
public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
return tx.read(withCriteria(forResourceServer(resourceServerId)
.compare(SearchableFields.SCOPE_ID, Operator.IN, scopeIds)))
public List<Policy> findByScopes(ResourceServer resourceServer, List<Scope> scopes) {
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.SCOPE_ID, Operator.IN, scopes.stream().map(Scope::getId))))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer) {
DefaultModelCriteria<Policy> mcb = forResourceServer(resourceServerId)
public void findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes, Consumer<Policy> consumer) {
DefaultModelCriteria<Policy> mcb = forResourceServer(resourceServer)
.compare(SearchableFields.TYPE, Operator.EQ, "scope")
.compare(SearchableFields.SCOPE_ID, Operator.IN, scopeIds);
.compare(SearchableFields.SCOPE_ID, Operator.IN, scopes.stream().map(Scope::getId));
if (resourceId != null) {
mcb = mcb.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resourceId);
if (resource != null) {
mcb = mcb.compare(SearchableFields.RESOURCE_ID, Operator.EQ, resource.getId());
// @NamedQuery(name="findPolicyIdByNullResourceScope", query="PolicyEntity pe left join fetch pe.config c inner join pe.scopes s where pe.resourceServer.id = :serverId and pe.type = 'scope' and pe.resources is empty and s.id in (:scopeIds) and not exists (select pec from pe.config pec where KEY(pec) = 'defaultResourceType')"),
} else {
mcb = mcb.compare(SearchableFields.RESOURCE_ID, Operator.NOT_EXISTS)
@ -237,16 +239,16 @@ public class MapPolicyStore implements PolicyStore {
}
@Override
public List<Policy> findByType(String type, String resourceServerId) {
return tx.read(withCriteria(forResourceServer(resourceServerId)
public List<Policy> findByType(ResourceServer resourceServer, String type) {
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.TYPE, Operator.EQ, type)))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<Policy> findDependentPolicies(String id, String resourceServerId) {
return tx.read(withCriteria(forResourceServer(resourceServerId)
public List<Policy> findDependentPolicies(ResourceServer resourceServer, String id) {
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.ASSOCIATED_POLICY_ID, Operator.EQ, id)))
.map(this::entityToAdapter)
.collect(Collectors.toList());

View file

@ -29,6 +29,7 @@ import org.keycloak.authorization.store.PolicyStore;
import org.keycloak.authorization.store.ResourceServerStore;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.authorization.store.ScopeStore;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.ModelException;
@ -40,17 +41,14 @@ import org.keycloak.models.map.storage.MapStorage;
import org.keycloak.storage.StorageId;
import static org.keycloak.common.util.StackUtil.getShortStackTrace;
import org.keycloak.models.ClientModel;
public class MapResourceServerStore implements ResourceServerStore {
private static final Logger LOG = Logger.getLogger(MapResourceServerStore.class);
private final AuthorizationProvider authorizationProvider;
final MapKeycloakTransaction<MapResourceServerEntity, ResourceServer> tx;
private final MapStorage<MapResourceServerEntity, ResourceServer> resourceServerStore;
public MapResourceServerStore(KeycloakSession session, MapStorage<MapResourceServerEntity, ResourceServer> resourceServerStore, AuthorizationProvider provider) {
this.resourceServerStore = resourceServerStore;
this.tx = resourceServerStore.createTransaction(session);
this.authorizationProvider = provider;
session.getTransactionManager().enlist(tx);
@ -64,49 +62,53 @@ public class MapResourceServerStore implements ResourceServerStore {
@Override
public ResourceServer create(ClientModel client) {
LOG.tracef("create(%s)%s", client.getClientId(), getShortStackTrace());
String clientId = client.getId();
LOG.tracef("create(%s)%s", clientId, getShortStackTrace());
if (clientId == null) return null;
if (!StorageId.isLocalStorage(clientId)) {
throw new ModelException("Creating resource server from federated ClientModel not supported");
}
if (tx.read(clientId) != null) {
throw new ModelDuplicateException("Resource server already exists: " + clientId);
if (findByClient(client) != null) {
throw new ModelDuplicateException("Resource server assiciated with client : " + client.getClientId() + " already exists.");
}
MapResourceServerEntity entity = new MapResourceServerEntityImpl();
entity.setId(clientId);
return entityToAdapter(tx.create(entity));
entity = tx.create(entity);
return entityToAdapter(entity);
}
@Override
public void delete(ClientModel client) {
String id = client.getId();
LOG.tracef("delete(%s, %s)%s", id, getShortStackTrace());
if (id == null) return;
LOG.tracef("delete(%s, %s)%s", client.getClientId(), getShortStackTrace());
ResourceServer resourceServer = findByClient(client);
if (resourceServer == null) return;
String id = resourceServer.getId();
// TODO: Simplify the following, ideally by leveraging triggers, stored procedures or ref integrity
PolicyStore policyStore = authorizationProvider.getStoreFactory().getPolicyStore();
policyStore.findByResourceServer(id).stream()
policyStore.findByResourceServer(resourceServer).stream()
.map(Policy::getId)
.forEach(policyStore::delete);
PermissionTicketStore permissionTicketStore = authorizationProvider.getStoreFactory().getPermissionTicketStore();
permissionTicketStore.findByResourceServer(id).stream()
permissionTicketStore.findByResourceServer(resourceServer).stream()
.map(PermissionTicket::getId)
.forEach(permissionTicketStore::delete);
ResourceStore resourceStore = authorizationProvider.getStoreFactory().getResourceStore();
resourceStore.findByResourceServer(id).stream()
resourceStore.findByResourceServer(resourceServer).stream()
.map(Resource::getId)
.forEach(resourceStore::delete);
ScopeStore scopeStore = authorizationProvider.getStoreFactory().getScopeStore();
scopeStore.findByResourceServer(id).stream()
scopeStore.findByResourceServer(resourceServer).stream()
.map(Scope::getId)
.forEach(scopeStore::delete);

View file

@ -22,6 +22,7 @@ import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.Resource.SearchableFields;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
@ -37,6 +38,7 @@ import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@ -62,20 +64,20 @@ public class MapResourceStore implements ResourceStore {
return new MapResourceAdapter(origEntity, authorizationProvider.getStoreFactory());
}
private DefaultModelCriteria<Resource> forResourceServer(String resourceServerId) {
private DefaultModelCriteria<Resource> forResourceServer(ResourceServer resourceServer) {
DefaultModelCriteria<Resource> mcb = criteria();
return resourceServerId == null
return resourceServer == null
? mcb
: mcb.compare(SearchableFields.RESOURCE_SERVER_ID, Operator.EQ,
resourceServerId);
resourceServer.getId());
}
@Override
public Resource create(String id, String name, ResourceServer resourceServer, String owner) {
public Resource create(ResourceServer resourceServer, String id, String name, String owner) {
LOG.tracef("create(%s, %s, %s, %s)%s", id, name, resourceServer, owner, getShortStackTrace());
// @UniqueConstraint(columnNames = {"NAME", "RESOURCE_SERVER_ID", "OWNER"})
DefaultModelCriteria<Resource> mcb = forResourceServer(resourceServer.getId())
DefaultModelCriteria<Resource> mcb = forResourceServer(resourceServer)
.compare(SearchableFields.NAME, Operator.EQ, name)
.compare(SearchableFields.OWNER, Operator.EQ, owner);
@ -102,10 +104,10 @@ public class MapResourceStore implements ResourceStore {
}
@Override
public Resource findById(String id, String resourceServerId) {
LOG.tracef("findById(%s, %s)%s", id, resourceServerId, getShortStackTrace());
public Resource findById(ResourceServer resourceServer, String id) {
LOG.tracef("findById(%s, %s)%s", id, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.ID, Operator.EQ, id)))
.findFirst()
.map(this::entityToAdapter)
@ -113,57 +115,57 @@ public class MapResourceStore implements ResourceStore {
}
@Override
public void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer) {
findByOwnerFilter(ownerId, resourceServerId, consumer, -1, -1);
public void findByOwner(ResourceServer resourceServer, String ownerId, Consumer<Resource> consumer) {
findByOwnerFilter(ownerId, resourceServer, consumer, -1, -1);
}
private void findByOwnerFilter(String ownerId, String resourceServerId, Consumer<Resource> consumer, int firstResult, int maxResult) {
LOG.tracef("findByOwnerFilter(%s, %s, %s, %d, %d)%s", ownerId, resourceServerId, consumer, firstResult, maxResult, getShortStackTrace());
private void findByOwnerFilter(String ownerId, ResourceServer resourceServer, Consumer<Resource> consumer, int firstResult, int maxResult) {
LOG.tracef("findByOwnerFilter(%s, %s, %s, %d, %d)%s", ownerId, resourceServer, consumer, firstResult, maxResult, getShortStackTrace());
tx.read(withCriteria(forResourceServer(resourceServerId).compare(SearchableFields.OWNER, Operator.EQ, ownerId))
tx.read(withCriteria(forResourceServer(resourceServer).compare(SearchableFields.OWNER, Operator.EQ, ownerId))
.pagination(firstResult, maxResult, SearchableFields.ID)
).map(this::entityToAdapter)
.forEach(consumer);
}
@Override
public List<Resource> findByOwner(String ownerId, String resourceServerId, int first, int max) {
public List<Resource> findByOwner(ResourceServer resourceServer, String ownerId, Integer firstResult, Integer maxResults) {
List<Resource> resourceList = new LinkedList<>();
findByOwnerFilter(ownerId, resourceServerId, resourceList::add, first, max);
findByOwnerFilter(ownerId, resourceServer, resourceList::add, firstResult, maxResults);
return resourceList;
}
@Override
public List<Resource> findByUri(String uri, String resourceServerId) {
LOG.tracef("findByUri(%s, %s)%s", uri, resourceServerId, getShortStackTrace());
public List<Resource> findByUri(ResourceServer resourceServer, String uri) {
LOG.tracef("findByUri(%s, %s)%s", uri, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.URI, Operator.EQ, uri)))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<Resource> findByResourceServer(String resourceServerId) {
LOG.tracef("findByResourceServer(%s)%s", resourceServerId, getShortStackTrace());
public List<Resource> findByResourceServer(ResourceServer resourceServer) {
LOG.tracef("findByResourceServer(%s)%s", resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)))
return tx.read(withCriteria(forResourceServer(resourceServer)))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<Resource> findByResourceServer(Map<Resource.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
LOG.tracef("findByResourceServer(%s, %s, %d, %d)%s", attributes, resourceServerId, firstResult, maxResult, getShortStackTrace());
DefaultModelCriteria<Resource> mcb = forResourceServer(resourceServerId).and(
public List<Resource> findByResourceServer(ResourceServer resourceServer, Map<Resource.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
LOG.tracef("findByResourceServer(%s, %s, %d, %d)%s", attributes, resourceServer, firstResult, maxResults, getShortStackTrace());
DefaultModelCriteria<Resource> mcb = forResourceServer(resourceServer).and(
attributes.entrySet().stream()
.map(this::filterEntryToDefaultModelCriteria)
.toArray(DefaultModelCriteria[]::new)
);
return tx.read(withCriteria(mcb).pagination(firstResult, maxResult, SearchableFields.NAME))
return tx.read(withCriteria(mcb).pagination(firstResult, maxResults, SearchableFields.NAME))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@ -194,24 +196,19 @@ public class MapResourceStore implements ResourceStore {
}
@Override
public void findByScope(List<String> scopes, String resourceServerId, Consumer<Resource> consumer) {
LOG.tracef("findByScope(%s, %s, %s)%s", scopes, resourceServerId, consumer, getShortStackTrace());
public void findByScopes(ResourceServer resourceServer, Set<Scope> scopes, Consumer<Resource> consumer) {
LOG.tracef("findByScope(%s, %s, %s)%s", scopes, resourceServer, consumer, getShortStackTrace());
tx.read(withCriteria(forResourceServer(resourceServerId)
.compare(SearchableFields.SCOPE_ID, Operator.IN, scopes)))
tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.SCOPE_ID, Operator.IN, scopes.stream().map(Scope::getId))))
.map(this::entityToAdapter)
.forEach(consumer);
}
@Override
public Resource findByName(String name, String resourceServerId) {
return findByName(name, resourceServerId, resourceServerId);
}
@Override
public Resource findByName(String name, String ownerId, String resourceServerId) {
LOG.tracef("findByName(%s, %s, %s)%s", name, ownerId, resourceServerId, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
public Resource findByName(ResourceServer resourceServer, String name, String ownerId) {
LOG.tracef("findByName(%s, %s, %s)%s", name, ownerId, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.OWNER, Operator.EQ, ownerId)
.compare(SearchableFields.NAME, Operator.EQ, name)))
.findFirst()
@ -220,19 +217,19 @@ public class MapResourceStore implements ResourceStore {
}
@Override
public void findByType(String type, String resourceServerId, Consumer<Resource> consumer) {
LOG.tracef("findByType(%s, %s, %s)%s", type, resourceServerId, consumer, getShortStackTrace());
tx.read(withCriteria(forResourceServer(resourceServerId)
public void findByType(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
LOG.tracef("findByType(%s, %s, %s)%s", type, resourceServer, consumer, getShortStackTrace());
tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.TYPE, Operator.EQ, type)))
.map(this::entityToAdapter)
.forEach(consumer);
}
@Override
public void findByType(String type, String owner, String resourceServerId, Consumer<Resource> consumer) {
LOG.tracef("findByType(%s, %s, %s, %s)%s", type, owner, resourceServerId, consumer, getShortStackTrace());
public void findByType(ResourceServer resourceServer, String type, String owner, Consumer<Resource> consumer) {
LOG.tracef("findByType(%s, %s, %s, %s)%s", type, owner, resourceServer, consumer, getShortStackTrace());
DefaultModelCriteria<Resource> mcb = forResourceServer(resourceServerId)
DefaultModelCriteria<Resource> mcb = forResourceServer(resourceServer)
.compare(SearchableFields.TYPE, Operator.EQ, type);
if (owner != null) {
@ -245,10 +242,10 @@ public class MapResourceStore implements ResourceStore {
}
@Override
public void findByTypeInstance(String type, String resourceServerId, Consumer<Resource> consumer) {
LOG.tracef("findByTypeInstance(%s, %s, %s)%s", type, resourceServerId, consumer, getShortStackTrace());
tx.read(withCriteria(forResourceServer(resourceServerId)
.compare(SearchableFields.OWNER, Operator.NE, resourceServerId)
public void findByTypeInstance(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
LOG.tracef("findByTypeInstance(%s, %s, %s)%s", type, resourceServer, consumer, getShortStackTrace());
tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.OWNER, Operator.NE, resourceServer.getClientId())
.compare(SearchableFields.TYPE, Operator.EQ, type)))
.map(this::entityToAdapter)
.forEach(consumer);

View file

@ -60,22 +60,22 @@ public class MapScopeStore implements ScopeStore {
return new MapScopeAdapter(origEntity, authorizationProvider.getStoreFactory());
}
private DefaultModelCriteria<Scope> forResourceServer(String resourceServerId) {
private DefaultModelCriteria<Scope> forResourceServer(ResourceServer resourceServer) {
DefaultModelCriteria<Scope> mcb = criteria();
return resourceServerId == null
return resourceServer == null
? mcb
: mcb.compare(SearchableFields.RESOURCE_SERVER_ID, Operator.EQ,
resourceServerId);
resourceServer.getId());
}
@Override
public Scope create(String id, String name, ResourceServer resourceServer) {
public Scope create(ResourceServer resourceServer, String id, String name) {
LOG.tracef("create(%s, %s, %s)%s", id, name, resourceServer, getShortStackTrace());
// @UniqueConstraint(columnNames = {"NAME", "RESOURCE_SERVER_ID"})
DefaultModelCriteria<Scope> mcb = forResourceServer(resourceServer.getId())
DefaultModelCriteria<Scope> mcb = forResourceServer(resourceServer)
.compare(SearchableFields.NAME, Operator.EQ, name);
if (tx.getCount(withCriteria(mcb)) > 0) {
@ -99,10 +99,10 @@ public class MapScopeStore implements ScopeStore {
}
@Override
public Scope findById(String id, String resourceServerId) {
LOG.tracef("findById(%s, %s)%s", id, resourceServerId, getShortStackTrace());
public Scope findById(ResourceServer resourceServer, String id) {
LOG.tracef("findById(%s, %s)%s", id, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId)
return tx.read(withCriteria(forResourceServer(resourceServer)
.compare(SearchableFields.ID, Operator.EQ, id)))
.findFirst()
.map(this::entityToAdapter)
@ -110,10 +110,10 @@ public class MapScopeStore implements ScopeStore {
}
@Override
public Scope findByName(String name, String resourceServerId) {
LOG.tracef("findByName(%s, %s)%s", name, resourceServerId, getShortStackTrace());
public Scope findByName(ResourceServer resourceServer, String name) {
LOG.tracef("findByName(%s, %s)%s", name, resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(resourceServerId).compare(SearchableFields.NAME,
return tx.read(withCriteria(forResourceServer(resourceServer).compare(SearchableFields.NAME,
Operator.EQ, name)))
.findFirst()
.map(this::entityToAdapter)
@ -121,17 +121,17 @@ public class MapScopeStore implements ScopeStore {
}
@Override
public List<Scope> findByResourceServer(String id) {
LOG.tracef("findByResourceServer(%s)%s", id, getShortStackTrace());
public List<Scope> findByResourceServer(ResourceServer resourceServer) {
LOG.tracef("findByResourceServer(%s)%s", resourceServer, getShortStackTrace());
return tx.read(withCriteria(forResourceServer(id)))
return tx.read(withCriteria(forResourceServer(resourceServer)))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}
@Override
public List<Scope> findByResourceServer(Map<Scope.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
DefaultModelCriteria<Scope> mcb = forResourceServer(resourceServerId);
public List<Scope> findByResourceServer(ResourceServer resourceServer, Map<Scope.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
DefaultModelCriteria<Scope> mcb = forResourceServer(resourceServer);
for (Scope.FilterOption filterOption : attributes.keySet()) {
String[] value = attributes.get(filterOption);
@ -148,7 +148,7 @@ public class MapScopeStore implements ScopeStore {
}
}
return tx.read(withCriteria(mcb).pagination(firstResult, maxResult, SearchableFields.NAME))
return tx.read(withCriteria(mcb).pagination(firstResult, maxResults, SearchableFields.NAME))
.map(this::entityToAdapter)
.collect(Collectors.toList());
}

View file

@ -51,13 +51,13 @@ public class MapPermissionTicketAdapter extends AbstractPermissionTicketModel<Ma
@Override
public Resource getResource() {
return storeFactory.getResourceStore().findById(entity.getResourceId(), entity.getResourceServerId());
return storeFactory.getResourceStore().findById(getResourceServer(), entity.getResourceId());
}
@Override
public Scope getScope() {
if (entity.getScopeId() == null) return null;
return storeFactory.getScopeStore().findById(entity.getScopeId(), entity.getResourceServerId());
return storeFactory.getScopeStore().findById(getResourceServer(), entity.getScopeId());
}
@Override
@ -89,7 +89,8 @@ public class MapPermissionTicketAdapter extends AbstractPermissionTicketModel<Ma
@Override
public Policy getPolicy() {
if (entity.getPolicyId() == null) return null;
return storeFactory.getPolicyStore().findById(entity.getPolicyId(), entity.getResourceServerId());
ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(entity.getResourceServerId());
return storeFactory.getPolicyStore().findById(resourceServer, entity.getPolicyId());
}
@Override

View file

@ -127,25 +127,25 @@ public class MapPolicyAdapter extends AbstractPolicyModel<MapPolicyEntity> {
String resourceServerId = entity.getResourceServerId();
Set<String> ids = entity.getAssociatedPolicyIds();
return ids == null ? Collections.emptySet() : ids.stream()
.map(policyId -> storeFactory.getPolicyStore().findById(policyId, resourceServerId))
.map(policyId -> storeFactory.getPolicyStore().findById(storeFactory.getResourceServerStore().findById(resourceServerId), policyId))
.collect(Collectors.toSet());
}
@Override
public Set<Resource> getResources() {
String resourceServerId = entity.getResourceServerId();
ResourceServer resourceServer = getResourceServer();
Set<String> ids = entity.getResourceIds();
return ids == null ? Collections.emptySet() : ids.stream()
.map(resourceId -> storeFactory.getResourceStore().findById(resourceId, resourceServerId))
.map(resourceId -> storeFactory.getResourceStore().findById(resourceServer, resourceId))
.collect(Collectors.toSet());
}
@Override
public Set<Scope> getScopes() {
String resourceServerId = entity.getResourceServerId();
ResourceServer resourceServer = getResourceServer();
Set<String> ids = entity.getScopeIds();
return ids == null ? Collections.emptySet() : ids.stream()
.map(scopeId -> storeFactory.getScopeStore().findById(scopeId, resourceServerId))
.map(scopeId -> storeFactory.getScopeStore().findById(resourceServer, scopeId))
.collect(Collectors.toSet());
}

View file

@ -18,6 +18,7 @@
package org.keycloak.models.map.authorization.adapter;
import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PermissionTicketStore;
import org.keycloak.authorization.store.PolicyStore;
@ -90,9 +91,10 @@ public class MapResourceAdapter extends AbstractResourceModel<MapResourceEntity>
@Override
public List<Scope> getScopes() {
Set<String> ids = entity.getScopeIds();
ResourceServer resourceServer = getResourceServer();
return ids == null ? Collections.emptyList() : ids.stream()
.map(id -> storeFactory
.getScopeStore().findById(id, entity.getResourceServerId()))
.getScopeStore().findById(resourceServer, id))
.collect(Collectors.toList());
}
@ -108,8 +110,8 @@ public class MapResourceAdapter extends AbstractResourceModel<MapResourceEntity>
}
@Override
public String getResourceServer() {
return entity.getResourceServerId();
public ResourceServer getResourceServer() {
return storeFactory.getResourceServerStore().findById(entity.getResourceServerId());
}
@Override
@ -141,13 +143,13 @@ public class MapResourceAdapter extends AbstractResourceModel<MapResourceEntity>
// The scope^ was removed from the Resource
// Remove permission tickets based on the scope
List<PermissionTicket> permissions = permissionStore.findByScope(scope.getId(), getResourceServer());
List<PermissionTicket> permissions = permissionStore.findByScope(getResourceServer(), scope);
for (PermissionTicket permission : permissions) {
permissionStore.delete(permission.getId());
}
// Remove the scope from each Policy for this Resource
policyStore.findByResource(getId(), getResourceServer(), policy -> policy.removeScope(scope));
policyStore.findByResource(getResourceServer(), this, policy -> policy.removeScope(scope));
}
}

View file

@ -47,7 +47,6 @@ import org.keycloak.models.map.storage.ModelCriteriaBuilder.Operator;
import org.keycloak.models.map.storage.criteria.DefaultModelCriteria;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.UserStorageManager;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.storage.client.ClientStorageProvider;
@ -684,7 +683,7 @@ public class MapUserProvider implements UserProvider.Streams, UserCredentialStor
authorizedGroups.removeIf(id -> {
Map<Resource.FilterOption, String[]> values = new EnumMap<>(Resource.FilterOption.class);
values.put(Resource.FilterOption.EXACT_NAME, new String[] {"group.resource." + id});
return resourceStore.findByResourceServer(values, null, 0, 1).isEmpty();
return resourceStore.findByResourceServer(null, values, 0, 1).isEmpty();
});
criteria = criteria.compare(SearchableFields.ASSIGNED_GROUP, Operator.IN, authorizedGroups);

View file

@ -242,20 +242,20 @@ public final class AuthorizationProvider implements Provider {
ScopeStore delegate = storeFactory.getScopeStore();
@Override
public Scope create(String name, ResourceServer resourceServer) {
return delegate.create(name, resourceServer);
public Scope create(ResourceServer resourceServer, String name) {
return delegate.create(resourceServer, name);
}
@Override
public Scope create(String id, String name, ResourceServer resourceServer) {
return delegate.create(id, name, resourceServer);
public Scope create(ResourceServer resourceServer, String id, String name) {
return delegate.create(resourceServer, id, name);
}
@Override
public void delete(String id) {
Scope scope = findById(id, null);
Scope scope = findById(null, id);
PermissionTicketStore ticketStore = AuthorizationProvider.this.getStoreFactory().getPermissionTicketStore();
List<PermissionTicket> permissions = ticketStore.findByScope(id, scope.getResourceServer().getId());
List<PermissionTicket> permissions = ticketStore.findByScope(scope.getResourceServer(), scope);
for (PermissionTicket permission : permissions) {
ticketStore.delete(permission.getId());
@ -265,23 +265,23 @@ public final class AuthorizationProvider implements Provider {
}
@Override
public Scope findById(String id, String resourceServerId) {
return delegate.findById(id, resourceServerId);
public Scope findById(ResourceServer resourceServer, String id) {
return delegate.findById(resourceServer, id);
}
@Override
public Scope findByName(String name, String resourceServerId) {
return delegate.findByName(name, resourceServerId);
public Scope findByName(ResourceServer resourceServer, String name) {
return delegate.findByName(resourceServer, name);
}
@Override
public List<Scope> findByResourceServer(String id) {
return delegate.findByResourceServer(id);
public List<Scope> findByResourceServer(ResourceServer resourceServer) {
return delegate.findByResourceServer(resourceServer);
}
@Override
public List<Scope> findByResourceServer(Map<Scope.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
return delegate.findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
public List<Scope> findByResourceServer(ResourceServer resourceServer, Map<Scope.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
return delegate.findByResourceServer(resourceServer, attributes, firstResult, maxResults);
}
};
}
@ -292,15 +292,15 @@ public final class AuthorizationProvider implements Provider {
PolicyStore policyStore = storeFactory.getPolicyStore();
@Override
public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
public Policy create(ResourceServer resourceServer, AbstractPolicyRepresentation representation) {
Set<String> resources = representation.getResources();
if (resources != null) {
representation.setResources(resources.stream().map(id -> {
Resource resource = storeFactory.getResourceStore().findById(id, resourceServer.getId());
Resource resource = storeFactory.getResourceStore().findById(resourceServer, id);
if (resource == null) {
resource = storeFactory.getResourceStore().findByName(id, resourceServer.getId());
resource = storeFactory.getResourceStore().findByName(resourceServer, id);
}
if (resource == null) {
@ -315,10 +315,10 @@ public final class AuthorizationProvider implements Provider {
if (scopes != null) {
representation.setScopes(scopes.stream().map(id -> {
Scope scope = storeFactory.getScopeStore().findById(id, resourceServer.getId());
Scope scope = storeFactory.getScopeStore().findById(resourceServer, id);
if (scope == null) {
scope = storeFactory.getScopeStore().findByName(id, resourceServer.getId());
scope = storeFactory.getScopeStore().findByName(resourceServer, id);
}
if (scope == null) {
@ -334,10 +334,10 @@ public final class AuthorizationProvider implements Provider {
if (policies != null) {
representation.setPolicies(policies.stream().map(id -> {
Policy policy = storeFactory.getPolicyStore().findById(id, resourceServer.getId());
Policy policy = storeFactory.getPolicyStore().findById(resourceServer, id);
if (policy == null) {
policy = storeFactory.getPolicyStore().findByName(id, resourceServer.getId());
policy = storeFactory.getPolicyStore().findByName(resourceServer, id);
}
if (policy == null) {
@ -348,12 +348,12 @@ public final class AuthorizationProvider implements Provider {
}).collect(Collectors.toSet()));
}
return RepresentationToModel.toModel(representation, AuthorizationProvider.this, policyStore.create(representation, resourceServer));
return RepresentationToModel.toModel(representation, AuthorizationProvider.this, policyStore.create(resourceServer, representation));
}
@Override
public void delete(String id) {
Policy policy = findById(id, null);
Policy policy = findById(null, id);
if (policy != null) {
ResourceServer resourceServer = policy.getResourceServer();
@ -369,7 +369,7 @@ public final class AuthorizationProvider implements Provider {
}
}
findDependentPolicies(policy.getId(), resourceServer.getId()).forEach(dependentPolicy -> {
findDependentPolicies(resourceServer, policy.getId()).forEach(dependentPolicy -> {
dependentPolicy.removeAssociatedPolicy(policy);
if (dependentPolicy.getAssociatedPolicies().isEmpty()) {
delete(dependentPolicy.getId());
@ -381,68 +381,68 @@ public final class AuthorizationProvider implements Provider {
}
@Override
public Policy findById(String id, String resourceServerId) {
return policyStore.findById(id, resourceServerId);
public Policy findById(ResourceServer resourceServer, String id) {
return policyStore.findById(resourceServer, id);
}
@Override
public Policy findByName(String name, String resourceServerId) {
return policyStore.findByName(name, resourceServerId);
public Policy findByName(ResourceServer resourceServer, String name) {
return policyStore.findByName(resourceServer, name);
}
@Override
public List<Policy> findByResourceServer(String resourceServerId) {
return policyStore.findByResourceServer(resourceServerId);
public List<Policy> findByResourceServer(ResourceServer resourceServer) {
return policyStore.findByResourceServer(resourceServer);
}
@Override
public List<Policy> findByResourceServer(Map<Policy.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
return policyStore.findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
public List<Policy> findByResourceServer(ResourceServer resourceServer, Map<Policy.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
return policyStore.findByResourceServer(resourceServer, attributes, firstResult, maxResults);
}
@Override
public List<Policy> findByResource(String resourceId, String resourceServerId) {
return policyStore.findByResource(resourceId, resourceServerId);
public List<Policy> findByResource(ResourceServer resourceServer, Resource resource) {
return policyStore.findByResource(resourceServer, resource);
}
@Override
public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
policyStore.findByResource(resourceId, resourceServerId, consumer);
public void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer) {
policyStore.findByResource(resourceServer, resource, consumer);
}
@Override
public List<Policy> findByResourceType(String resourceType, String resourceServerId) {
return policyStore.findByResourceType(resourceType, resourceServerId);
public List<Policy> findByResourceType(ResourceServer resourceServer, String resourceType) {
return policyStore.findByResourceType(resourceServer, resourceType);
}
@Override
public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
return policyStore.findByScopeIds(scopeIds, resourceServerId);
public List<Policy> findByScopes(ResourceServer resourceServer, List<Scope> scopes) {
return policyStore.findByScopes(resourceServer, scopes);
}
@Override
public List<Policy> findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId) {
return policyStore.findByScopeIds(scopeIds, resourceId, resourceServerId);
public List<Policy> findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes) {
return policyStore.findByScopes(resourceServer, resource, scopes);
}
@Override
public void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer) {
policyStore.findByScopeIds(scopeIds, resourceId, resourceServerId, consumer);
public void findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes, Consumer<Policy> consumer) {
policyStore.findByScopes(resourceServer, resource, scopes, consumer);
}
@Override
public List<Policy> findByType(String type, String resourceServerId) {
return policyStore.findByType(type, resourceServerId);
public List<Policy> findByType(ResourceServer resourceServer, String type) {
return policyStore.findByType(resourceServer, type);
}
@Override
public List<Policy> findDependentPolicies(String id, String resourceServerId) {
return policyStore.findDependentPolicies(id, resourceServerId);
public List<Policy> findDependentPolicies(ResourceServer resourceServer, String id) {
return policyStore.findDependentPolicies(resourceServer, id);
}
@Override
public void findByResourceType(String type, String id, Consumer<Policy> policyConsumer) {
policyStore.findByResourceType(type, id, policyConsumer);
public void findByResourceType(ResourceServer resourceServer, String type, Consumer<Policy> policyConsumer) {
policyStore.findByResourceType(resourceServer, type, policyConsumer);
}
};
}
@ -452,28 +452,28 @@ public final class AuthorizationProvider implements Provider {
ResourceStore delegate = storeFactory.getResourceStore();
@Override
public Resource create(String name, ResourceServer resourceServer, String owner) {
return delegate.create(name, resourceServer, owner);
public Resource create(ResourceServer resourceServer, String name, String owner) {
return delegate.create(resourceServer, name, owner);
}
@Override
public Resource create(String id, String name, ResourceServer resourceServer, String owner) {
return delegate.create(id, name, resourceServer, owner);
public Resource create(ResourceServer resourceServer, String id, String name, String owner) {
return delegate.create(resourceServer, id, name, owner);
}
@Override
public void delete(String id) {
Resource resource = findById(id, null);
Resource resource = findById(null, id);
StoreFactory storeFactory = AuthorizationProvider.this.getStoreFactory();
PermissionTicketStore ticketStore = storeFactory.getPermissionTicketStore();
List<PermissionTicket> permissions = ticketStore.findByResource(id, resource.getResourceServer());
List<PermissionTicket> permissions = ticketStore.findByResource(resource.getResourceServer(), resource);
for (PermissionTicket permission : permissions) {
ticketStore.delete(permission.getId());
}
PolicyStore policyStore = storeFactory.getPolicyStore();
List<Policy> policies = policyStore.findByResource(id, resource.getResourceServer());
List<Policy> policies = policyStore.findByResource(resource.getResourceServer(), resource);
for (Policy policyModel : policies) {
if (policyModel.getResources().size() == 1) {
@ -487,88 +487,83 @@ public final class AuthorizationProvider implements Provider {
}
@Override
public Resource findById(String id, String resourceServerId) {
return delegate.findById(id, resourceServerId);
public Resource findById(ResourceServer resourceServer, String id) {
return delegate.findById(resourceServer, id);
}
@Override
public List<Resource> findByOwner(String ownerId, String resourceServerId) {
return delegate.findByOwner(ownerId, resourceServerId);
public List<Resource> findByOwner(ResourceServer resourceServer, String ownerId) {
return delegate.findByOwner(resourceServer, ownerId);
}
@Override
public void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer) {
delegate.findByOwner(ownerId, resourceServerId, consumer);
public void findByOwner(ResourceServer resourceServer, String ownerId, Consumer<Resource> consumer) {
delegate.findByOwner(resourceServer, ownerId, consumer);
}
@Override
public List<Resource> findByOwner(String ownerId, String resourceServerId, int first, int max) {
return delegate.findByOwner(ownerId, resourceServerId, first, max);
public List<Resource> findByOwner(ResourceServer resourceServer, String ownerId, Integer firstResult, Integer maxResults) {
return delegate.findByOwner(resourceServer, ownerId, firstResult, maxResults);
}
@Override
public List<Resource> findByUri(String uri, String resourceServerId) {
return delegate.findByUri(uri, resourceServerId);
public List<Resource> findByUri(ResourceServer resourceServer, String uri) {
return delegate.findByUri(resourceServer, uri);
}
@Override
public List<Resource> findByResourceServer(String resourceServerId) {
return delegate.findByResourceServer(resourceServerId);
public List<Resource> findByResourceServer(ResourceServer resourceServer) {
return delegate.findByResourceServer(resourceServer);
}
@Override
public List<Resource> findByResourceServer(Map<Resource.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
return delegate.findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
public List<Resource> findByResourceServer(ResourceServer resourceServer, Map<Resource.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults) {
return delegate.findByResourceServer(resourceServer, attributes, firstResult, maxResults);
}
@Override
public List<Resource> findByScope(List<String> id, String resourceServerId) {
return delegate.findByScope(id, resourceServerId);
public List<Resource> findByScopes(ResourceServer resourceServer, Set<Scope> scopes) {
return delegate.findByScopes(resourceServer, scopes);
}
@Override
public void findByScope(List<String> scopes, String resourceServerId, Consumer<Resource> consumer) {
delegate.findByScope(scopes, resourceServerId, consumer);
public void findByScopes(ResourceServer resourceServer, Set<Scope> scopes, Consumer<Resource> consumer) {
delegate.findByScopes(resourceServer, scopes, consumer);
}
@Override
public Resource findByName(String name, String resourceServerId) {
return delegate.findByName(name, resourceServerId);
public Resource findByName(ResourceServer resourceServer, String name, String ownerId) {
return delegate.findByName(resourceServer, name, ownerId);
}
@Override
public Resource findByName(String name, String ownerId, String resourceServerId) {
return delegate.findByName(name, ownerId, resourceServerId);
public List<Resource> findByType(ResourceServer resourceServer, String type) {
return delegate.findByType(resourceServer, type);
}
@Override
public List<Resource> findByType(String type, String resourceServerId) {
return delegate.findByType(type, resourceServerId);
public void findByType(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
delegate.findByType(resourceServer, type, consumer);
}
@Override
public void findByType(String type, String resourceServerId, Consumer<Resource> consumer) {
delegate.findByType(type, resourceServerId, consumer);
public void findByType(ResourceServer resourceServer, String type, String owner, Consumer<Resource> consumer) {
delegate.findByType(resourceServer, type, owner, consumer);
}
@Override
public void findByType(String type, String owner, String resourceServerId, Consumer<Resource> consumer) {
delegate.findByType(type, owner, resourceServerId, consumer);
public List<Resource> findByType(ResourceServer resourceServer, String type, String owner) {
return delegate.findByType(resourceServer, type);
}
@Override
public List<Resource> findByType(String type, String owner, String resourceServerId) {
return delegate.findByType(type, resourceServerId);
public List<Resource> findByTypeInstance(ResourceServer resourceServer, String type) {
return delegate.findByTypeInstance(resourceServer, type);
}
@Override
public List<Resource> findByTypeInstance(String type, String resourceServerId) {
return delegate.findByTypeInstance(type, resourceServerId);
}
@Override
public void findByTypeInstance(String type, String resourceServerId, Consumer<Resource> consumer) {
delegate.findByTypeInstance(type, resourceServerId, consumer);
public void findByTypeInstance(ResourceServer resourceServer, String type, Consumer<Resource> consumer) {
delegate.findByTypeInstance(resourceServer, type, consumer);
}
};
}

View file

@ -46,7 +46,7 @@ public class UserManagedPermissionUtil {
filter.put(PermissionTicket.FilterOption.RESOURCE_ID, ticket.getResource().getId());
filter.put(PermissionTicket.FilterOption.POLICY_IS_NOT_NULL, Boolean.TRUE.toString());
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().find(filter, ticket.getResourceServer().getId(), -1, 1);
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().find(ticket.getResourceServer(), filter, null, null);
if (!tickets.isEmpty()) {
policy = tickets.iterator().next().getPolicy();
@ -80,7 +80,7 @@ public class UserManagedPermissionUtil {
filter.put(PermissionTicket.FilterOption.RESOURCE_ID, ticket.getResource().getId());
filter.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().find(filter, ticket.getResourceServer().getId(), -1, -1);
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().find(ticket.getResourceServer(), filter, null, null);
if (tickets.isEmpty()) {
PolicyStore policyStore = storeFactory.getPolicyStore();
@ -103,7 +103,7 @@ public class UserManagedPermissionUtil {
userPolicyRep.setName(KeycloakModelUtils.generateId());
userPolicyRep.addUser(ticket.getRequester());
Policy userPolicy = policyStore.create(userPolicyRep, ticket.getResourceServer());
Policy userPolicy = policyStore.create(ticket.getResourceServer(), userPolicyRep);
userPolicy.setOwner(ticket.getOwner());
@ -113,7 +113,7 @@ public class UserManagedPermissionUtil {
policyRep.setType("uma");
policyRep.addPolicy(userPolicy.getId());
Policy policy = policyStore.create(policyRep, ticket.getResourceServer());
Policy policy = policyStore.create(ticket.getResourceServer(), policyRep);
policy.setOwner(ticket.getOwner());
policy.addResource(ticket.getResource());

View file

@ -163,7 +163,7 @@ public interface Resource {
*
* @return the resource server associated with this resource
*/
String getResourceServer();
ResourceServer getResourceServer();
/**
* Returns the resource's owner, which is usually an identifier that uniquely identifies the resource's owner.

View file

@ -18,10 +18,19 @@
package org.keycloak.authorization.model;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.representations.idm.authorization.DecisionStrategy;
import org.keycloak.representations.idm.authorization.PolicyEnforcementMode;
import org.keycloak.storage.SearchableModelField;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* Represents a resource server, whose resources are managed and protected. A resource server is basically an existing
* client application in Keycloak that will also act as a resource server.
@ -83,4 +92,11 @@ public interface ResourceServer {
* @return the decision strategy
*/
DecisionStrategy getDecisionStrategy();
/**
* Returns id of a client that this {@link ResourceServer} is associated with
*/
default String getClientId() {
return getId();
}
}

View file

@ -25,6 +25,7 @@ import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
@ -73,16 +74,16 @@ public final class Permissions {
}
// obtain all resources where owner is the resource server
resourceStore.findByOwner(resourceServer.getId(), resourceServer.getId(), resource -> {
resourceStore.findByOwner(resourceServer, resourceServer.getClientId(), resource -> {
if (limit.decrementAndGet() >= 0) {
evaluator.accept(createResourcePermissions(resource, resourceServer, resource.getScopes(), authorization, request));
}
});
// resource server isn't current user
if (resourceServer.getId() != identity.getId()) {
if (!Objects.equals(resourceServer.getClientId(), identity.getId())) {
// obtain all resources where owner is the current user
resourceStore.findByOwner(identity.getId(), resourceServer.getId(), resource -> {
resourceStore.findByOwner(resourceServer, identity.getId(), resource -> {
if (limit.decrementAndGet() >= 0) {
evaluator.accept(createResourcePermissions(resource, resourceServer, resource.getScopes(), authorization, request));
}
@ -90,7 +91,7 @@ public final class Permissions {
}
// obtain all resources granted to the user via permission tickets (uma)
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().findGranted(identity.getId(), resourceServer.getId());
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().findGranted(resourceServer, identity.getId());
if (!tickets.isEmpty()) {
Map<String, ResourcePermission> userManagedPermissions = new HashMap<>();
@ -151,7 +152,7 @@ public final class Permissions {
// is owned by the resource server itself
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceStore resourceStore = storeFactory.getResourceStore();
resourceStore.findByType(type, resourceServer.getId(), resource1 -> {
resourceStore.findByType(resourceServer, type, resource1 -> {
for (Scope typeScope : resource1.getScopes()) {
if (!scopes.contains(typeScope)) {
scopes.add(typeScope);

View file

@ -170,7 +170,7 @@ public class DecisionPermissionCollector extends AbstractDecisionCollector {
return true;
}
return resource != null && !resource.getOwner().equals(resourceServer.getId());
return resource != null && !resource.getOwner().equals(resourceServer.getClientId());
}
public Collection<Permission> results() {
@ -191,7 +191,7 @@ public class DecisionPermissionCollector extends AbstractDecisionCollector {
} else if (!grantedScopes.isEmpty()) {
ResourceStore resourceStore = authorizationProvider.getStoreFactory().getResourceStore();
resourceStore.findByScope(grantedScopes.stream().map(Scope::getId).collect(Collectors.toList()), resourceServer.getId(), resource1 -> permissions.add(createPermission(resource, scopeNames, permission.getClaims(), request)));
resourceStore.findByScopes(resourceServer, new HashSet<>(grantedScopes), resource1 -> permissions.add(createPermission(resource, scopeNames, permission.getClaims(), request)));
permissions.add(createPermission(null, scopeNames, permission.getClaims(), request));
}

View file

@ -19,6 +19,7 @@
package org.keycloak.authorization.policy.evaluation;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
@ -67,14 +68,14 @@ public class DefaultPolicyEvaluator implements PolicyEvaluator {
Resource resource = permission.getResource();
if (resource != null) {
policyStore.findByResource(resource.getId(), resourceServer.getId(), policyConsumer);
policyStore.findByResource(resourceServer, resource, policyConsumer);
if (resource.getType() != null) {
policyStore.findByResourceType(resource.getType(), resourceServer.getId(), policyConsumer);
policyStore.findByResourceType(resourceServer, resource.getType(), policyConsumer);
if (!resource.getOwner().equals(resourceServer.getId())) {
for (Resource typedResource : resourceStore.findByType(resource.getType(), resourceServer.getId())) {
policyStore.findByResource(typedResource.getId(), resourceServer.getId(), policyConsumer);
if (!resource.getOwner().equals(resourceServer.getClientId())) {
for (Resource typedResource : resourceStore.findByType(resourceServer, resource.getType())) {
policyStore.findByResource(resourceServer, typedResource, policyConsumer);
}
}
}
@ -83,7 +84,7 @@ public class DefaultPolicyEvaluator implements PolicyEvaluator {
Collection<Scope> scopes = permission.getScopes();
if (!scopes.isEmpty()) {
policyStore.findByScopeIds(scopes.stream().map(Scope::getId).collect(Collectors.toList()), null, resourceServer.getId(), policyConsumer);
policyStore.findByScopes(resourceServer, null, new LinkedList<>(scopes), policyConsumer);
}
if (verified.get()) {

View file

@ -93,13 +93,13 @@ public class PermissionTicketAwareDecisionResultCollector extends DecisionPermis
if (permissions != null) {
for (Permission permission : permissions) {
Resource resource = resourceStore.findById(permission.getResourceId(), resourceServer.getId());
Resource resource = resourceStore.findById(resourceServer, permission.getResourceId());
if (resource == null) {
resource = resourceStore.findByName(permission.getResourceId(), identity.getId(), resourceServer.getId());
resource = resourceStore.findByName(resourceServer, permission.getResourceId(), identity.getId());
}
if (resource == null || !resource.isOwnerManagedAccess() || resource.getOwner().equals(identity.getId()) || resource.getOwner().equals(resourceServer.getId())) {
if (resource == null || !resource.isOwnerManagedAccess() || resource.getOwner().equals(identity.getId()) || resource.getOwner().equals(resourceServer.getClientId())) {
continue;
}
@ -116,19 +116,19 @@ public class PermissionTicketAwareDecisionResultCollector extends DecisionPermis
filters.put(PermissionTicket.FilterOption.REQUESTER, identity.getId());
filters.put(PermissionTicket.FilterOption.SCOPE_IS_NULL, Boolean.TRUE.toString());
List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(filters, resource.getResourceServer(), -1, -1);
List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(resource.getResourceServer(), filters, null, null);
if (tickets.isEmpty()) {
authorization.getStoreFactory().getPermissionTicketStore().create(resource.getId(), null, identity.getId(), resourceServer);
authorization.getStoreFactory().getPermissionTicketStore().create(resourceServer, resource, null, identity.getId());
}
} else {
ScopeStore scopeStore = authorization.getStoreFactory().getScopeStore();
for (String scopeId : scopes) {
Scope scope = scopeStore.findByName(scopeId, resourceServer.getId());
Scope scope = scopeStore.findByName(resourceServer, scopeId);
if (scope == null) {
scope = scopeStore.findById(scopeId, resourceServer.getId());
scope = scopeStore.findById(resourceServer, scopeId);
}
Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
@ -137,10 +137,10 @@ public class PermissionTicketAwareDecisionResultCollector extends DecisionPermis
filters.put(PermissionTicket.FilterOption.REQUESTER, identity.getId());
filters.put(PermissionTicket.FilterOption.SCOPE_ID, scope.getId());
List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(filters, resource.getResourceServer(), -1, -1);
List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(resource.getResourceServer(), filters, null, null);
if (tickets.isEmpty()) {
authorization.getStoreFactory().getPermissionTicketStore().create(resource.getId(), scope.getId(), identity.getId(), resourceServer);
authorization.getStoreFactory().getPermissionTicketStore().create(resourceServer, resource, scope, identity.getId());
}
}
}

View file

@ -23,6 +23,7 @@ import java.util.Map;
import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
/**
* A {@link PermissionTicketStore} is responsible to manage the persistence of {@link org.keycloak.authorization.model.PermissionTicket} instances.
@ -34,21 +35,23 @@ public interface PermissionTicketStore {
/**
* Returns count of {@link PermissionTicket}, filtered by the given attributes.
*
* @param resourceServer the resource server
* @param attributes permission tickets that do not match the attributes are not included with the count; possible filter options are given by {@link PermissionTicket.FilterOption}
* @param resourceServerId the resource server id
* @return an integer indicating the amount of permission tickets
* @throws IllegalArgumentException when there is an unknown attribute in the {@code attributes} map
*/
long count(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId);
long count(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes);
/**
* Creates a new {@link PermissionTicket} instance.
*
* @param permission the policy representation
* @param resourceServer the resource server to which this policy belongs
* @param resource resource id
* @param scope scope id
* @param requester the policy representation
* @return a new instance of {@link PermissionTicket}
*/
PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer);
PermissionTicket create(ResourceServer resourceServer, Resource resource, Scope scope, String requester);
/**
* Deletes a permission from the underlying persistence mechanism.
@ -60,97 +63,103 @@ public interface PermissionTicketStore {
/**
* Returns a {@link PermissionTicket} with the given <code>id</code>
*
* @param resourceServer the resource server
* @param id the identifier of the permission
* @param resourceServerId the resource server id
* @return a permission with the given identifier.
*/
PermissionTicket findById(String id, String resourceServerId);
PermissionTicket findById(ResourceServer resourceServer, String id);
/**
* Returns a list of {@link PermissionTicket} associated with a {@link ResourceServer} with the given <code>resourceServerId</code>.
* Returns a list of {@link PermissionTicket} associated with a {@link ResourceServer}.
*
* @param resourceServerId the identifier of a resource server
* @param resourceServer the resource server
* @return a list of permissions belonging to the given resource server
*/
List<PermissionTicket> findByResourceServer(String resourceServerId);
List<PermissionTicket> findByResourceServer(ResourceServer resourceServer);
/**
* Returns a list of {@link PermissionTicket} associated with the given <code>owner</code>.
*
* @param resourceServer the resource server
* @param owner the identifier of a resource server
* @return a list of permissions belonging to the given owner
*/
List<PermissionTicket> findByOwner(String owner, String resourceServerId);
List<PermissionTicket> findByOwner(ResourceServer resourceServer, String owner);
/**
* Returns a list of {@link PermissionTicket} associated with a {@link org.keycloak.authorization.core.model.Resource} with the given <code>resourceId</code>.
* Returns a list of {@link PermissionTicket} associated with the {@link org.keycloak.authorization.model.Resource resource}.
*
* @param resourceId the identifier of a resource
* @param resourceServerId the resource server id
* @param resourceServer the resource server
* @param resource the resource
* @return a list of permissions associated with the given resource
* TODO: maybe we can get rid of reosourceServer param here as resource has method getResourceServer()
*/
List<PermissionTicket> findByResource(String resourceId, String resourceServerId);
List<PermissionTicket> findByResource(ResourceServer resourceServer, Resource resource);
/**
* Returns a list of {@link PermissionTicket} associated with a {@link org.keycloak.authorization.core.model.Scope} with the given <code>scopeId</code>.
* Returns a list of {@link PermissionTicket} associated with the {@link org.keycloak.authorization.model.Scope scope}.
*
* @param scopeId the id of the scopes
* @param resourceServerId the resource server id
* @param resourceServer the resource server
* @param scope the scope
* @return a list of permissions associated with the given scopes
*
* TODO: maybe we can get rid of reosourceServer param here as resource has method getResourceServer()
*/
List<PermissionTicket> findByScope(String scopeId, String resourceServerId);
List<PermissionTicket> findByScope(ResourceServer resourceServer, Scope scope);
/**
* Returns a list of {@link PermissionTicket}, filtered by the given attributes.
*
* @param resourceServer a resource server that resulting tickets should belong to. Ignored if {@code null}
* @param attributes a map of keys and values to filter on; possible filter options are given by {@link PermissionTicket.FilterOption}
* @param resourceServerId an id of resource server that resulting tickets should belong to. Ignored if {@code null}
* @param firstResult first result to return; Ignored if negative or zero
* @param maxResult maximum number of results to return; Ignored if negative
* @param firstResult first result to return. Ignored if negative or {@code null}.
* @param maxResults maximum number of results to return. Ignored if negative or {@code null}.
* @return a list of filtered and paginated permissions
*
* @throws IllegalArgumentException when there is an unknown attribute in the {@code attributes} map
*
*/
List<PermissionTicket> find(Map<PermissionTicket.FilterOption, String> attributes, String resourceServerId, int firstResult, int maxResult);
List<PermissionTicket> find(ResourceServer resourceServer, Map<PermissionTicket.FilterOption, String> attributes, Integer firstResult, Integer maxResults);
/**
* Returns a list of {@link PermissionTicket} granted to the given {@code userId}.
*
* @param resourceServer the resource server
* @param userId the user id
* @param resourceServerId the resource server id
* @return a list of permissions granted for a particular user
*/
List<PermissionTicket> findGranted(String userId, String resourceServerId);
List<PermissionTicket> findGranted(ResourceServer resourceServer, String userId);
/**
* Returns a list of {@link PermissionTicket} with name equal to {@code resourceName} granted to the given {@code userId}.
*
* @param resourceServer the resource server
* @param resourceName the name of a resource
* @param userId the user id
* @param resourceServerId the resource server id
* @return a list of permissions granted for a particular user
*
* TODO: investigate a way how to replace resourceName with Resource class
*/
List<PermissionTicket> findGranted(String resourceName, String userId, String resourceServerId);
List<PermissionTicket> findGranted(ResourceServer resourceServer, String resourceName, String userId);
/**
* Returns a list of {@link Resource} granted to the given {@code requester}
*
* @param requester the requester
* @param name the keyword to query resources by name or null if any resource
* @param first first result
* @param max max result
* @param firstResult first result to return. Ignored if negative or {@code null}.
* @param maxResults maximum number of results to return. Ignored if negative or {@code null}.
* @return a list of {@link Resource} granted to the given {@code requester}
*/
List<Resource> findGrantedResources(String requester, String name, int first, int max);
List<Resource> findGrantedResources(String requester, String name, Integer firstResult, Integer maxResults);
/**
* Returns a list of {@link Resource} granted by the owner to other users
*
* @param owner the owner
* @param first first result
* @param max max result
* @param firstResult first result to return. Ignored if negative or {@code null}.
* @param maxResults maximum number of results to return. Ignored if negative or {@code null}.
* @return a list of {@link Resource} granted by the owner
*/
List<Resource> findGrantedOwnerResources(String owner, int first, int max);
List<Resource> findGrantedOwnerResources(String owner, Integer firstResult, Integer maxResults);
}

View file

@ -24,7 +24,9 @@ import java.util.Map;
import java.util.function.Consumer;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation;
/**
@ -38,11 +40,11 @@ public interface PolicyStore {
* Creates a new {@link Policy} instance. The new instance is not necessarily persisted though, which may require
* a call to the {#save} method to actually make it persistent.
*
* @param representation the policy representation
* @param resourceServer the resource server to which this policy belongs
* @param representation the policy representation
* @return a new instance of {@link Policy}
*/
Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer);
Policy create(ResourceServer resourceServer, AbstractPolicyRepresentation representation);
/**
* Deletes a policy from the underlying persistence mechanism.
@ -54,121 +56,137 @@ public interface PolicyStore {
/**
* Returns a {@link Policy} with the given <code>id</code>
*
* @param resourceServer the resource server
* @param id the identifier of the policy
* @param resourceServerId the resource server id
* @return a policy with the given identifier.
*/
Policy findById(String id, String resourceServerId);
Policy findById(ResourceServer resourceServer, String id);
/**
* Returns a {@link Policy} with the given <code>name</code>
*
* @param resourceServer the resource server
* @param name the name of the policy
* @param resourceServerId the resource server id
* @return a policy with the given name.
*/
Policy findByName(String name, String resourceServerId);
Policy findByName(ResourceServer resourceServer, String name);
/**
* Returns a list of {@link Policy} associated with a {@link ResourceServer} with the given <code>resourceServerId</code>.
*
* @param resourceServerId the identifier of a resource server
* @param resourceServer the identifier of a resource server
* @return a list of policies that belong to the given resource server
*/
List<Policy> findByResourceServer(String resourceServerId);
List<Policy> findByResourceServer(ResourceServer resourceServer);
/**
* Returns a list of {@link Policy} associated with a {@link ResourceServer} with the given <code>resourceServerId</code>.
*
* @param resourceServer the identifier of a resource server
* @param attributes a map holding the attributes that will be used as a filter; possible filter options are given by {@link Policy.FilterOption}
* @param resourceServerId the identifier of a resource server
* @param firstResult first result to return. Ignored if negative or {@code null}.
* @param maxResults maximum number of results to return. Ignored if negative or {@code null}.
* @return a list of policies that belong to the given resource server
*
* @throws IllegalArgumentException when there is an unknown attribute in the {@code attributes} map
*/
List<Policy> findByResourceServer(Map<Policy.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult);
List<Policy> findByResourceServer(ResourceServer resourceServer, Map<Policy.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults);
/**
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.core.model.Resource} with the given <code>resourceId</code>.
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Resource} with the given <code>resourceId</code>.
*
* @param resourceId the identifier of a resource
* @param resourceServerId the resource server id
* @param resourceServer the resource server
* @param resource the resource
* @return a list of policies associated with the given resource
*/
default List<Policy> findByResource(String resourceId, String resourceServerId) {
default List<Policy> findByResource(ResourceServer resourceServer, Resource resource) {
List<Policy> result = new LinkedList<>();
findByResource(resourceId, resourceServerId, result::add);
findByResource(resourceServer, resource, result::add);
return result;
}
void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer);
/**
* Searches for all policies associated with the {@link org.keycloak.authorization.model.Resource} and passes the result to the {@code consumer}
*
* @param resourceServer the resourceServer
* @param resource the resource
* @param consumer consumer of policies resulted from the search
*/
void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer);
/**
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.core.model.Resource} with the given <code>type</code>.
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.ResourceServer} with the given <code>type</code>.
*
* @param resourceType the type of a resource
* @param resourceServerId the resource server id
* @param resourceServer the resource server id
* @param resourceType the type of a resource
* @return a list of policies associated with the given resource type
*/
default List<Policy> findByResourceType(String resourceType, String resourceServerId) {
default List<Policy> findByResourceType(ResourceServer resourceServer, String resourceType) {
List<Policy> result = new LinkedList<>();
findByResourceType(resourceType, resourceServerId, result::add);
findByResourceType((ResourceServer) null, resourceType, result::add);
return result;
}
/**
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.core.model.Scope} with the given <code>scopeIds</code>.
* Searches for policies associated with a {@link org.keycloak.authorization.model.ResourceServer} and passes the result to the consumer
*
* @param scopeIds the id of the scopes
* @param resourceServerId the resource server id
* @return a list of policies associated with the given scopes
* @param resourceServer the resourceServer
* @param type the type of a resource
* @param policyConsumer consumer of policies resulted from the search
*/
List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId);
void findByResourceType(ResourceServer resourceServer, String type, Consumer<Policy> policyConsumer);
/**
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.core.model.Scope} with the given <code>resourceId</code> and <code>scopeIds</code>.
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Scope} within the given <code>scope</code>.
*
* @param scopeIds the id of the scopes
* @param resourceId the id of the resource. Ignored if {@code null}.
* @param resourceServerId the resource server id
* @param resourceServer the resource server
* @param scopes the scopes
* @return a list of policies associated with the given scopes
*/
default List<Policy> findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId) {
List<Policy> findByScopes(ResourceServer resourceServer, List<Scope> scopes);
/**
* Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Scope} with the given <code>resource</code> and <code>scopes</code>.
*
* @param resourceServer the resource server
* @param resource the resource. Ignored if {@code null}.
* @param scopes the scopes
* @return a list of policies associated with the given scopes
*/
default List<Policy> findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes) {
List<Policy> result = new LinkedList<>();
findByScopeIds(scopeIds, resourceId, resourceServerId, result::add);
findByScopes(resourceServer, resource, scopes, result::add);
return result;
}
/**
* Effectively the same method as {@link #findByScopeIds(List, String, String)}, however in the end
* Effectively the same method as {@link #findByScopes(ResourceServer, Resource, List)}, however in the end
* the {@code consumer} is fed with the result.
*
*/
void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer);
void findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes, Consumer<Policy> consumer);
/**
* Returns a list of {@link Policy} with the given <code>type</code>.
*
* @param resourceServer the resource server id
* @param type the type of the policy
* @param resourceServerId the resource server id
* @return a list of policies with the given type
*/
List<Policy> findByType(String type, String resourceServerId);
List<Policy> findByType(ResourceServer resourceServer, String type);
/**
* Returns a list of {@link Policy} that depends on another policy with the given <code>id</code>.
*
* @param resourceServer the resource server
* @param id the id of the policy to query its dependents
* @param resourceServerId the resource server id
* @return a list of policies that depends on the a policy with the given identifier
*/
List<Policy> findDependentPolicies(String id, String resourceServerId);
void findByResourceType(String type, String resourceServerId, Consumer<Policy> policyConsumer);
List<Policy> findDependentPolicies(ResourceServer resourceServer, String id);
}

View file

@ -50,9 +50,7 @@ public interface ResourceServerStore {
* @param id the identifier of an existing resource server instance
*
* @return the resource server instance with the given identifier or null if no instance was found
* @deprecated use {@code findByClient} instead.
*/
@Deprecated
ResourceServer findById(String id);
/**

View file

@ -19,11 +19,13 @@ package org.keycloak.authorization.store;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/**
@ -36,25 +38,25 @@ public interface ResourceStore {
/**
* <p>Creates a {@link Resource} instance backed by this persistent storage implementation.
*
* @param name the name of this resource. It must be unique.
* @param resourceServer the resource server to where the given resource belongs to
* @param name the name of this resource. It must be unique.
* @param owner the owner of this resource or null if the resource server is the owner
* @return an instance backed by the underlying storage implementation
*/
default Resource create(String name, ResourceServer resourceServer, String owner) {
return create(null, name, resourceServer, owner);
default Resource create(ResourceServer resourceServer, String name, String owner) {
return create(resourceServer, null, name, owner);
}
/**
* <p>Creates a {@link Resource} instance backed by this persistent storage implementation.
*
* @param resourceServer the resource server to where the given resource belongs to
* @param id the id of this resource. It must be unique. Will be randomly generated if null.
* @param name the name of this resource. It must be unique.
* @param resourceServer the resource server to where the given resource belongs to
* @param owner the owner of this resource or null if the resource server is the owner
* @return an instance backed by the underlying storage implementation
*/
Resource create(String id, String name, ResourceServer resourceServer, String owner);
Resource create(ResourceServer resourceServer, String id, String name, String owner);
/**
* Removes a {@link Resource} instance, with the given {@code id} from the persistent storage.
@ -66,101 +68,114 @@ public interface ResourceStore {
/**
* Returns a {@link Resource} instance based on its identifier.
*
* @param resourceServer the resource server
* @param id the identifier of an existing resource instance
* @return the resource instance with the given identifier or null if no instance was found
*/
Resource findById(String id, String resourceServerId);
Resource findById(ResourceServer resourceServer, String id);
/**
* Finds all {@link Resource} instances with the given {@code ownerId}.
*
*
* @param resourceServer
* @param ownerId the identifier of the owner
* @return a list with all resource instances owned by the given owner
*/
default List<Resource> findByOwner(String ownerId, String resourceServerId) {
default List<Resource> findByOwner(ResourceServer resourceServer, String ownerId) {
List<Resource> list = new LinkedList<>();
findByOwner(ownerId, resourceServerId, list::add);
findByOwner(resourceServer, ownerId, list::add);
return list;
}
void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer);
void findByOwner(ResourceServer resourceServer, String ownerId, Consumer<Resource> consumer);
List<Resource> findByOwner(String ownerId, String resourceServerId, int first, int max);
List<Resource> findByOwner(ResourceServer resourceServer, String ownerId, Integer firstResult, Integer maxResults);
/**
* Finds all {@link Resource} instances with the given uri.
*
*
* @param resourceServer
* @param uri the identifier of the uri
* @return a list with all resource instances owned by the given owner
*/
List<Resource> findByUri(String uri, String resourceServerId);
List<Resource> findByUri(ResourceServer resourceServer, String uri);
/**
* Finds all {@link Resource} instances associated with a given resource server.
*
* @param resourceServerId the identifier of the resource server
* @param resourceServer the identifier of the resource server
* @return a list with all resources associated with the given resource server
*/
List<Resource> findByResourceServer(String resourceServerId);
List<Resource> findByResourceServer(ResourceServer resourceServer);
/**
* Finds all {@link Resource} instances associated with a given resource server.
*
* @param resourceServer the identifier of the resource server
* @param attributes a map holding the attributes that will be used as a filter; possible filter options are given by {@link Resource.FilterOption}
* @param resourceServerId the identifier of the resource server
* @param firstResult first result to return. Ignored if negative or {@code null}.
* @param maxResults maximum number of results to return. Ignored if negative or {@code null}.
* @return a list with all resources associated with the given resource server
*
* @throws IllegalArgumentException when there is an unknown attribute in the {@code attributes} map
*/
List<Resource> findByResourceServer(Map<Resource.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult);
List<Resource> findByResourceServer(ResourceServer resourceServer, Map<Resource.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults);
/**
* Finds all {@link Resource} associated with a given scope.
*
* @param id one or more scope identifiers
*
* @param resourceServer
* @param scopes one or more scope identifiers
* @return a list of resources associated with the given scope(s)
*/
default List<Resource> findByScope(List<String> id, String resourceServerId) {
default List<Resource> findByScopes(ResourceServer resourceServer, Set<Scope> scopes) {
List<Resource> result = new ArrayList<>();
findByScope(id, resourceServerId, result::add);
findByScopes(resourceServer, scopes, result::add);
return result;
}
void findByScope(List<String> scopes, String resourceServerId, Consumer<Resource> consumer);
void findByScopes(ResourceServer resourceServer, Set<Scope> scopes, Consumer<Resource> consumer);
/**
* Find a {@link Resource} by its name where the owner is the resource server itself.
*
* @param resourceServer the resource server
* @param name the name of the resource
* @param resourceServerId the identifier of the resource server
* @return a resource with the given name
*/
Resource findByName(String name, String resourceServerId);
default Resource findByName(ResourceServer resourceServer, String name) {
return findByName(resourceServer, name, resourceServer.getClientId());
}
/**
* Find a {@link Resource} by its name where the owner is the given <code>ownerId</code>.
*
* @param resourceServer the identifier of the resource server
* @param name the name of the resource
* @param ownerId the owner id
* @param resourceServerId the identifier of the resource server
* @return a resource with the given name
*/
Resource findByName(String name, String ownerId, String resourceServerId);
Resource findByName(ResourceServer resourceServer, String name, String ownerId);
/**
* Finds all {@link Resource} with the given type.
*
*
* @param resourceServer
* @param type the type of the resource
* @return a list of resources with the given type
*/
default List<Resource> findByType(String type, String resourceServerId) {
default List<Resource> findByType(ResourceServer resourceServer, String type) {
List<Resource> list = new LinkedList<>();
findByType(type, resourceServerId, list::add);
findByType(resourceServer, type, list::add);
return list;
}
@ -168,14 +183,16 @@ public interface ResourceStore {
/**
* Finds all {@link Resource} with the given type.
*
*
* @param resourceServer
* @param type the type of the resource
* @param owner the resource owner or null for any resource with a given type
* @return a list of resources with the given type
*/
default List<Resource> findByType(String type, String owner, String resourceServerId) {
default List<Resource> findByType(ResourceServer resourceServer, String type, String owner) {
List<Resource> list = new LinkedList<>();
findByType(type, owner, resourceServerId, list::add);
findByType(resourceServer, type, owner, list::add);
return list;
}
@ -183,31 +200,31 @@ public interface ResourceStore {
/**
* Finds all {@link Resource} with the given type.
*
* @param resourceServer the resource server id
* @param type the type of the resource
* @param resourceServerId the resource server id
* @param consumer the result consumer
* @return a list of resources with the given type
*/
void findByType(String type, String resourceServerId, Consumer<Resource> consumer);
void findByType(ResourceServer resourceServer, String type, Consumer<Resource> consumer);
/**
* Finds all {@link Resource} with the given type.
*
* @param resourceServer the resource server id
* @param type the type of the resource
* @param owner the resource owner or null for any resource with a given type
* @param resourceServerId the resource server id
* @param consumer the result consumer
* @return a list of resources with the given type
*/
void findByType(String type, String owner, String resourceServerId, Consumer<Resource> consumer);
void findByType(ResourceServer resourceServer, String type, String owner, Consumer<Resource> consumer);
default List<Resource> findByTypeInstance(String type, String resourceServerId) {
default List<Resource> findByTypeInstance(ResourceServer resourceServer, String type) {
List<Resource> list = new LinkedList<>();
findByTypeInstance(type, resourceServerId, list::add);
findByTypeInstance(resourceServer, type, list::add);
return list;
}
void findByTypeInstance(String type, String resourceServerId, Consumer<Resource> consumer);
void findByTypeInstance(ResourceServer resourceServerId, String type, Consumer<Resource> consumer);
}

View file

@ -35,26 +35,26 @@ public interface ScopeStore {
* Creates a new {@link Scope} instance. The new instance is not necessarily persisted though, which may require
* a call to the {#save} method to actually make it persistent.
*
* @param name the name of the scope
* @param resourceServer the resource server to which this scope belongs
*
* @param name the name of the scope
* @return a new instance of {@link Scope}
*/
default Scope create(String name, ResourceServer resourceServer) {
return create(null, name, resourceServer);
default Scope create(ResourceServer resourceServer, String name) {
return create(resourceServer, null, name);
}
/**
* Creates a new {@link Scope} instance. The new instance is not necessarily persisted though, which may require
* a call to the {#save} method to actually make it persistent.
*
* @param id the id of the scope. Is generated randomly when null
* @param name the name of the scope
* @param resourceServer the resource server to which this scope belongs
*
* @param id the id of the scope. Is generated randomly when null
* @param name the name of the scope
* @return a new instance of {@link Scope}
*/
Scope create(String id, String name, ResourceServer resourceServer);
Scope create(ResourceServer resourceServer, String id, String name);
/**
* Deletes a scope from the underlying persistence mechanism.
@ -66,40 +66,42 @@ public interface ScopeStore {
/**
* Returns a {@link Scope} with the given <code>id</code>
*
* @param resourceServer the resource server id
* @param id the identifier of the scope
* @param resourceServerId the resource server id
* @return a scope with the given identifier.
*/
Scope findById(String id, String resourceServerId);
Scope findById(ResourceServer resourceServer, String id);
/**
* Returns a {@link Scope} with the given <code>name</code>
*
* @param resourceServer the resource server
* @param name the name of the scope
*
* @param resourceServerId the resource server id
* @return a scope with the given name.
*/
Scope findByName(String name, String resourceServerId);
Scope findByName(ResourceServer resourceServer, String name);
/**
* Returns a list of {@link Scope} associated with a {@link ResourceServer} with the given <code>resourceServerId</code>.
* Returns a list of {@link Scope} associated with a {@link ResourceServer} with the given <code>resourceServer</code>.
*
* @param resourceServerId the identifier of a resource server
* @param resourceServer the identifier of a resource server
*
* @return a list of scopes that belong to the given resource server
*/
List<Scope> findByResourceServer(String id);
List<Scope> findByResourceServer(ResourceServer resourceServer);
/**
* Returns a list of {@link Scope} associated with a {@link ResourceServer} with the given <code>resourceServerId</code>.
*
* @param resourceServer the resource server
* @param attributes a map holding the attributes that will be used as a filter; possible filter options are given by {@link Scope.FilterOption}
* @param resourceServerId the identifier of a resource server
* @param firstResult first result to return. Ignored if negative or {@code null}.
* @param maxResults maximum number of results to return. Ignored if negative or {@code null}.
* @return a list of scopes that belong to the given resource server
*
* @throws IllegalArgumentException when there is an unknown attribute in the {@code attributes} map
*
*/
List<Scope> findByResourceServer(Map<Scope.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult);
List<Scope> findByResourceServer(ResourceServer resourceServer, Map<Scope.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults);
}

View file

@ -62,7 +62,7 @@ public class ClientApplicationSynchronizer implements Synchronizer<ClientRemoved
attributes.put(Policy.FilterOption.CONFIG, new String[] {"clients", event.getClient().getId()});
attributes.put(Policy.FilterOption.ANY_OWNER, Policy.FilterOption.EMPTY_FILTER);
List<Policy> search = storeFactory.getPolicyStore().findByResourceServer(attributes, null, -1, -1);
List<Policy> search = storeFactory.getPolicyStore().findByResourceServer(null, attributes, null, null);
for (Policy policy : search) {
PolicyProviderFactory policyFactory = authorizationProvider.getProviderFactory(policy.getType());

View file

@ -51,7 +51,7 @@ public class GroupSynchronizer implements Synchronizer<GroupModel.GroupRemovedEv
attributes.put(Policy.FilterOption.CONFIG, new String[] {"groups", group.getId()});
attributes.put(Policy.FilterOption.ANY_OWNER, Policy.FilterOption.EMPTY_FILTER);
List<Policy> search = policyStore.findByResourceServer(attributes, null, -1, -1);
List<Policy> search = policyStore.findByResourceServer(null, attributes, null, null);
for (Policy policy : search) {
PolicyProviderFactory policyFactory = authorizationProvider.getProviderFactory(policy.getType());

View file

@ -60,7 +60,7 @@ public class UserSynchronizer implements Synchronizer<UserRemovedEvent> {
attributes.put(Policy.FilterOption.TYPE, new String[] {"user"});
attributes.put(Policy.FilterOption.CONFIG, new String[] {"users", userModel.getId()});
List<Policy> search = policyStore.findByResourceServer(attributes, null, -1, -1);
List<Policy> search = policyStore.findByResourceServer(null, attributes, null, null);
for (Policy policy : search) {
PolicyProviderFactory policyFactory = authorizationProvider.getProviderFactory(policy.getType());
@ -84,9 +84,9 @@ public class UserSynchronizer implements Synchronizer<UserRemovedEvent> {
ResourceStore resourceStore = storeFactory.getResourceStore();
UserModel userModel = event.getUser();
resourceStore.findByOwner(userModel.getId(), null, resource -> {
resourceStore.findByOwner(null, userModel.getId(), resource -> {
String resourceId = resource.getId();
policyStore.findByResource(resourceId, resource.getResourceServer()).forEach(policy -> {
policyStore.findByResource(resource.getResourceServer(), resource).forEach(policy -> {
if (policy.getResources().size() == 1) {
policyStore.delete(policy.getId());
} else {
@ -105,7 +105,7 @@ public class UserSynchronizer implements Synchronizer<UserRemovedEvent> {
attributes.put(PermissionTicket.FilterOption.OWNER, userModel.getId());
for (PermissionTicket ticket : ticketStore.find(attributes, null, -1, -1)) {
for (PermissionTicket ticket : ticketStore.find(null, attributes, null, null)) {
ticketStore.delete(ticket.getId());
}
@ -113,7 +113,7 @@ public class UserSynchronizer implements Synchronizer<UserRemovedEvent> {
attributes.put(PermissionTicket.FilterOption.REQUESTER, userModel.getId());
for (PermissionTicket ticket : ticketStore.find(attributes, null, -1, -1)) {
for (PermissionTicket ticket : ticketStore.find(null, attributes, null, null)) {
ticketStore.delete(ticket.getId());
}
}

View file

@ -78,7 +78,7 @@ public class MigrateTo2_1_0 implements Migration {
ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
if (resourceServer != null) {
policyStore.findByType("role", resourceServer.getId()).forEach(policy -> {
policyStore.findByType(resourceServer, "role").forEach(policy -> {
Map<String, String> config = new HashMap(policy.getConfig());
String roles = config.get("roles");
List roleConfig;

View file

@ -910,7 +910,7 @@ public class ModelToRepresentation {
ResourceServerRepresentation server = new ResourceServerRepresentation();
server.setId(model.getId());
server.setClientId(model.getId());
server.setClientId(model.getClientId());
server.setName(client.getClientId());
server.setAllowRemoteResourceManagement(model.isAllowRemoteResourceManagement());
server.setPolicyEnforcementMode(model.getPolicyEnforcementMode());
@ -953,8 +953,9 @@ public class ModelToRepresentation {
representation.setLogic(policy.getLogic());
if (allFields) {
representation.setResourcesData(policy.getResources().stream().map(
resource -> toRepresentation(resource, resource.getResourceServer(), authorization, true)).collect(Collectors.toSet()));
representation.setResourcesData(policy.getResources().stream()
.map(resource -> toRepresentation(resource, policy.getResourceServer(), authorization, true))
.collect(Collectors.toSet()));
representation.setScopesData(policy.getScopes().stream().map(
resource -> toRepresentation(resource)).collect(Collectors.toSet()));
}
@ -962,11 +963,11 @@ public class ModelToRepresentation {
return representation;
}
public static ResourceRepresentation toRepresentation(Resource model, String resourceServer, AuthorizationProvider authorization) {
public static ResourceRepresentation toRepresentation(Resource model, ResourceServer resourceServer, AuthorizationProvider authorization) {
return toRepresentation(model, resourceServer, authorization, true);
}
public static ResourceRepresentation toRepresentation(Resource model, String resourceServer, AuthorizationProvider authorization, Boolean deep) {
public static ResourceRepresentation toRepresentation(Resource model, ResourceServer resourceServer, AuthorizationProvider authorization, Boolean deep) {
ResourceRepresentation resource = new ResourceRepresentation();
resource.setId(model.getId());
@ -984,8 +985,8 @@ public class ModelToRepresentation {
KeycloakSession keycloakSession = authorization.getKeycloakSession();
RealmModel realm = authorization.getRealm();
if (owner.getId().equals(resourceServer)) {
ClientModel clientModel = realm.getClientById(resourceServer);
if (owner.getId().equals(resourceServer.getClientId())) {
ClientModel clientModel = realm.getClientById(resourceServer.getClientId());
owner.setName(clientModel.getClientId());
} else {
UserModel userModel = keycloakSession.users().getUserById(realm, owner.getId());

View file

@ -2324,7 +2324,7 @@ public class RepresentationToModel {
if (owner == null) {
owner = new ResourceOwnerRepresentation();
owner.setId(resourceServer.getId());
owner.setId(resourceServer.getClientId());
resource.setOwner(owner);
} else if (owner.getName() != null) {
UserModel user = session.users().getUserByUsername(realm, owner.getName());
@ -2359,10 +2359,10 @@ public class RepresentationToModel {
Set<String> policyIds = new HashSet<>();
for (String policyName : policies) {
Policy policy = policyStore.findByName(policyName, resourceServer.getId());
Policy policy = policyStore.findByName(resourceServer, policyName);
if (policy == null) {
policy = policyStore.findById(policyName, resourceServer.getId());
policy = policyStore.findById(resourceServer, policyName);
}
if (policy == null) {
@ -2382,14 +2382,14 @@ public class RepresentationToModel {
}
PolicyStore policyStore = storeFactory.getPolicyStore();
Policy policy = policyStore.findById(policyRepresentation.getId(), resourceServer.getId());
Policy policy = policyStore.findById(resourceServer, policyRepresentation.getId());
if (policy == null) {
policy = policyStore.findByName(policyRepresentation.getName(), resourceServer.getId());
policy = policyStore.findByName(resourceServer, policyRepresentation.getName());
}
if (policy == null) {
policy = policyStore.create(policyRepresentation, resourceServer);
policy = policyStore.create(resourceServer, policyRepresentation);
} else {
policy = toModel(policyRepresentation, authorization, policy);
}
@ -2494,10 +2494,10 @@ public class RepresentationToModel {
}
if (!hasScope) {
ResourceServer resourceServer = policy.getResourceServer();
Scope scope = storeFactory.getScopeStore().findById(scopeId, resourceServer.getId());
Scope scope = storeFactory.getScopeStore().findById(resourceServer, scopeId);
if (scope == null) {
scope = storeFactory.getScopeStore().findByName(scopeId, resourceServer.getId());
scope = storeFactory.getScopeStore().findByName(resourceServer, scopeId);
if (scope == null) {
throw new RuntimeException("Scope with id or name [" + scopeId + "] does not exist");
}
@ -2547,10 +2547,10 @@ public class RepresentationToModel {
}
if (!hasPolicy) {
Policy associatedPolicy = policyStore.findById(policyId, resourceServer.getId());
Policy associatedPolicy = policyStore.findById(resourceServer, policyId);
if (associatedPolicy == null) {
associatedPolicy = policyStore.findByName(policyId, resourceServer.getId());
associatedPolicy = policyStore.findByName(resourceServer, policyId);
if (associatedPolicy == null) {
throw new RuntimeException("Policy with id or name [" + policyId + "] does not exist");
}
@ -2592,10 +2592,10 @@ public class RepresentationToModel {
}
}
if (!hasResource && !"".equals(resourceId)) {
Resource resource = storeFactory.getResourceStore().findById(resourceId, policy.getResourceServer().getId());
Resource resource = storeFactory.getResourceStore().findById(policy.getResourceServer(), resourceId);
if (resource == null) {
resource = storeFactory.getResourceStore().findByName(resourceId, policy.getResourceServer().getId());
resource = storeFactory.getResourceStore().findByName(policy.getResourceServer(), resourceId);
if (resource == null) {
throw new RuntimeException("Resource with id or name [" + resourceId + "] does not exist or is not owned by the resource server");
}
@ -2629,16 +2629,16 @@ public class RepresentationToModel {
if (owner == null) {
owner = new ResourceOwnerRepresentation();
owner.setId(resourceServer.getId());
owner.setId(resourceServer.getClientId());
}
String ownerId = owner.getId();
if (ownerId == null) {
ownerId = resourceServer.getId();
ownerId = resourceServer.getClientId();
}
if (!resourceServer.getId().equals(ownerId)) {
if (!resourceServer.getClientId().equals(ownerId)) {
RealmModel realm = authorization.getRealm();
KeycloakSession keycloakSession = authorization.getKeycloakSession();
UserProvider users = keycloakSession.users();
@ -2658,9 +2658,9 @@ public class RepresentationToModel {
Resource existing;
if (resource.getId() != null) {
existing = resourceStore.findById(resource.getId(), resourceServer.getId());
existing = resourceStore.findById(resourceServer, resource.getId());
} else {
existing = resourceStore.findByName(resource.getName(), ownerId, resourceServer.getId());
existing = resourceStore.findByName(resourceServer, resource.getName(), ownerId);
}
if (existing != null) {
@ -2695,7 +2695,7 @@ public class RepresentationToModel {
return existing;
}
Resource model = resourceStore.create(resource.getId(), resource.getName(), resourceServer, ownerId);
Resource model = resourceStore.create(resourceServer, resource.getId(), resource.getName(), ownerId);
model.setDisplayName(resource.getDisplayName());
model.setType(resource.getType());
@ -2732,9 +2732,9 @@ public class RepresentationToModel {
Scope existing;
if (scope.getId() != null) {
existing = scopeStore.findById(scope.getId(), resourceServer.getId());
existing = scopeStore.findById(resourceServer, scope.getId());
} else {
existing = scopeStore.findByName(scope.getName(), resourceServer.getId());
existing = scopeStore.findByName(resourceServer, scope.getName());
}
if (existing != null) {
@ -2746,7 +2746,7 @@ public class RepresentationToModel {
return existing;
}
Scope model = scopeStore.create(scope.getId(), scope.getName(), resourceServer);
Scope model = scopeStore.create(resourceServer, scope.getId(), scope.getName());
model.setDisplayName(scope.getDisplayName());
model.setIconUri(scope.getIconUri());
@ -2756,9 +2756,9 @@ public class RepresentationToModel {
return model;
}
public static PermissionTicket toModel(PermissionTicketRepresentation representation, String resourceServerId, AuthorizationProvider authorization) {
public static PermissionTicket toModel(PermissionTicketRepresentation representation, ResourceServer resourceServer, AuthorizationProvider authorization) {
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
PermissionTicket ticket = ticketStore.findById(representation.getId(), resourceServerId);
PermissionTicket ticket = ticketStore.findById(resourceServer, representation.getId());
boolean granted = representation.isGranted();
if (granted && !ticket.isGranted()) {

View file

@ -172,21 +172,21 @@ public class PolicyEvaluationService {
ScopeStore scopeStore = storeFactory.getScopeStore();
Set<Scope> scopes = givenScopes.stream().map(scopeRepresentation -> scopeStore.findByName(scopeRepresentation.getName(), resourceServer.getId())).collect(Collectors.toSet());
Set<Scope> scopes = givenScopes.stream().map(scopeRepresentation -> scopeStore.findByName(resourceServer, scopeRepresentation.getName())).collect(Collectors.toSet());
if (resource.getId() != null) {
Resource resourceModel = storeFactory.getResourceStore().findById(resource.getId(), resourceServer.getId());
Resource resourceModel = storeFactory.getResourceStore().findById(resourceServer, resource.getId());
return new ArrayList<>(Arrays.asList(
Permissions.createResourcePermissions(resourceModel, resourceServer, scopes, authorization, request))).stream();
} else if (resource.getType() != null) {
return storeFactory.getResourceStore().findByType(resource.getType(), resourceServer.getId()).stream().map(resource1 -> Permissions.createResourcePermissions(resource1,
return storeFactory.getResourceStore().findByType(resourceServer, resource.getType()).stream().map(resource1 -> Permissions.createResourcePermissions(resource1,
resourceServer, scopes, authorization, request));
} else {
if (scopes.isEmpty()) {
return Stream.empty();
}
List<Resource> resources = storeFactory.getResourceStore().findByScope(scopes.stream().map(Scope::getId).collect(Collectors.toList()), resourceServer.getId());
List<Resource> resources = storeFactory.getResourceStore().findByScopes(resourceServer, scopes);
if (resources.isEmpty()) {
return scopes.stream().map(scope -> new ResourcePermission(null, new ArrayList<>(Arrays.asList(scope)), resourceServer));
@ -254,7 +254,7 @@ public class PolicyEvaluationService {
String clientId = representation.getClientId();
if (clientId == null) {
clientId = resourceServer.getId();
clientId = resourceServer.getClientId();
}
if (clientId != null) {
@ -287,7 +287,7 @@ public class PolicyEvaluationService {
}
if (client == null) {
client = realm.getClientById(resourceServer.getId());
client = realm.getClientById(resourceServer.getClientId());
}
accessToken.issuedFor(client.getClientId());

View file

@ -39,7 +39,6 @@ import org.keycloak.authorization.store.PolicyStore;
import org.keycloak.authorization.store.StoreFactory;
import org.keycloak.events.admin.OperationType;
import org.keycloak.events.admin.ResourceType;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.models.utils.RepresentationToModel;
import org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation;
@ -155,7 +154,7 @@ public class PolicyResourceService {
return Response.status(Status.NOT_FOUND).build();
}
List<Policy> policies = authorization.getStoreFactory().getPolicyStore().findDependentPolicies(policy.getId(), resourceServer.getId());
List<Policy> policies = authorization.getStoreFactory().getPolicyStore().findDependentPolicies(resourceServer, policy.getId());
return Response.ok(policies.stream().map(policy -> {
PolicyRepresentation representation1 = new PolicyRepresentation();

View file

@ -88,7 +88,7 @@ public class PolicyService {
return doCreatePolicyTypeResource(type);
}
Policy policy = authorization.getStoreFactory().getPolicyStore().findById(type, resourceServer.getId());
Policy policy = authorization.getStoreFactory().getPolicyStore().findById(resourceServer, type);
return doCreatePolicyResource(policy);
}
@ -134,13 +134,13 @@ public class PolicyService {
public Policy create(AbstractPolicyRepresentation representation) {
PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
Policy existing = policyStore.findByName(representation.getName(), resourceServer.getId());
Policy existing = policyStore.findByName(resourceServer, representation.getName());
if (existing != null) {
throw new ErrorResponseException("Policy with name [" + representation.getName() + "] already exists", "Conflicting policy", Status.CONFLICT);
}
return policyStore.create(representation, resourceServer);
return policyStore.create(resourceServer, representation);
}
@Path("/search")
@ -158,7 +158,7 @@ public class PolicyService {
return Response.status(Status.BAD_REQUEST).build();
}
Policy model = storeFactory.getPolicyStore().findByName(name, this.resourceServer.getId());
Policy model = storeFactory.getPolicyStore().findByName(this.resourceServer, name);
if (model == null) {
return Response.noContent().build();
@ -206,7 +206,7 @@ public class PolicyService {
if (resource != null && !"".equals(resource.trim())) {
ResourceStore resourceStore = storeFactory.getResourceStore();
Resource resourceModel = resourceStore.findById(resource, resourceServer.getId());
Resource resourceModel = resourceStore.findById(resourceServer, resource);
if (resourceModel == null) {
Map<Resource.FilterOption, String[]> resourceFilters = new EnumMap<>(Resource.FilterOption.class);
@ -217,7 +217,7 @@ public class PolicyService {
resourceFilters.put(Resource.FilterOption.OWNER, new String[]{owner});
}
Set<String> resources = resourceStore.findByResourceServer(resourceFilters, resourceServer.getId(), -1, 1).stream().map(Resource::getId).collect(Collectors.toSet());
Set<String> resources = resourceStore.findByResourceServer(resourceServer, resourceFilters, -1, 1).stream().map(Resource::getId).collect(Collectors.toSet());
if (resources.isEmpty()) {
return Response.noContent().build();
@ -231,14 +231,14 @@ public class PolicyService {
if (scope != null && !"".equals(scope.trim())) {
ScopeStore scopeStore = storeFactory.getScopeStore();
Scope scopeModel = scopeStore.findById(scope, resourceServer.getId());
Scope scopeModel = scopeStore.findById(resourceServer, scope);
if (scopeModel == null) {
Map<Scope.FilterOption, String[]> scopeFilters = new EnumMap<>(Scope.FilterOption.class);
scopeFilters.put(Scope.FilterOption.NAME, new String[]{scope});
Set<String> scopes = scopeStore.findByResourceServer(scopeFilters, resourceServer.getId(), -1, 1).stream().map(Scope::getId).collect(Collectors.toSet());
Set<String> scopes = scopeStore.findByResourceServer(resourceServer, scopeFilters, -1, 1).stream().map(Scope::getId).collect(Collectors.toSet());
if (scopes.isEmpty()) {
return Response.noContent().build();
@ -265,7 +265,7 @@ public class PolicyService {
protected List<Object> doSearch(Integer firstResult, Integer maxResult, String fields, Map<Policy.FilterOption, String[]> filters) {
PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
return policyStore.findByResourceServer(filters, resourceServer.getId(), firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS).stream()
return policyStore.findByResourceServer(resourceServer, filters, firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS).stream()
.map(policy -> toRepresentation(policy, fields, authorization))
.collect(Collectors.toList());
}

View file

@ -113,7 +113,7 @@ public class ResourceSetService {
if (owner == null) {
owner = new ResourceOwnerRepresentation();
owner.setId(resourceServer.getId());
owner.setId(resourceServer.getClientId());
resource.setOwner(owner);
}
@ -123,13 +123,13 @@ public class ResourceSetService {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "You must specify the resource owner.", Status.BAD_REQUEST);
}
Resource existingResource = storeFactory.getResourceStore().findByName(resource.getName(), ownerId, this.resourceServer.getId());
Resource existingResource = storeFactory.getResourceStore().findByName(this.resourceServer, resource.getName(), ownerId);
if (existingResource != null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Resource with name [" + resource.getName() + "] already exists.", Status.CONFLICT);
}
return toRepresentation(toModel(resource, this.resourceServer, authorization), resourceServer.getId(), authorization);
return toRepresentation(toModel(resource, this.resourceServer, authorization), resourceServer, authorization);
}
@Path("{id}")
@ -141,7 +141,7 @@ public class ResourceSetService {
resource.setId(id);
StoreFactory storeFactory = this.authorization.getStoreFactory();
ResourceStore resourceStore = storeFactory.getResourceStore();
Resource model = resourceStore.findById(resource.getId(), resourceServer.getId());
Resource model = resourceStore.findById(resourceServer, resource.getId());
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -159,7 +159,7 @@ public class ResourceSetService {
public Response delete(@PathParam("id") String id) {
requireManage();
StoreFactory storeFactory = authorization.getStoreFactory();
Resource resource = storeFactory.getResourceStore().findById(id, resourceServer.getId());
Resource resource = storeFactory.getResourceStore().findById(resourceServer, id);
if (resource == null) {
return Response.status(Status.NOT_FOUND).build();
@ -167,7 +167,7 @@ public class ResourceSetService {
storeFactory.getResourceStore().delete(id);
audit(toRepresentation(resource, resourceServer.getId(), authorization), OperationType.DELETE);
audit(toRepresentation(resource, resourceServer, authorization), OperationType.DELETE);
return Response.noContent().build();
}
@ -177,13 +177,13 @@ public class ResourceSetService {
@NoCache
@Produces("application/json")
public Response findById(@PathParam("id") String id) {
return findById(id, resource -> toRepresentation(resource, resourceServer.getId(), authorization, true));
return findById(id, resource -> toRepresentation(resource, resourceServer, authorization, true));
}
public Response findById(String id, Function<Resource, ? extends ResourceRepresentation> toRepresentation) {
requireView();
StoreFactory storeFactory = authorization.getStoreFactory();
Resource model = storeFactory.getResourceStore().findById(id, resourceServer.getId());
Resource model = storeFactory.getResourceStore().findById(resourceServer, id);
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -199,7 +199,7 @@ public class ResourceSetService {
public Response getScopes(@PathParam("id") String id) {
requireView();
StoreFactory storeFactory = authorization.getStoreFactory();
Resource model = storeFactory.getResourceStore().findById(id, resourceServer.getId());
Resource model = storeFactory.getResourceStore().findById(resourceServer, id);
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -214,10 +214,10 @@ public class ResourceSetService {
return representation;
}).collect(Collectors.toList());
if (model.getType() != null && !model.getOwner().equals(resourceServer.getId())) {
if (model.getType() != null && !model.getOwner().equals(resourceServer.getClientId())) {
ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
for (Resource typed : resourceStore.findByType(model.getType(), resourceServer.getId())) {
if (typed.getOwner().equals(resourceServer.getId()) && !typed.getId().equals(model.getId())) {
for (Resource typed : resourceStore.findByType(resourceServer, model.getType())) {
if (typed.getOwner().equals(resourceServer.getClientId()) && !typed.getId().equals(model.getId())) {
scopes.addAll(typed.getScopes().stream().map(model1 -> {
ScopeRepresentation scope = new ScopeRepresentation();
scope.setId(model1.getId());
@ -243,7 +243,7 @@ public class ResourceSetService {
requireView();
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceStore resourceStore = storeFactory.getResourceStore();
Resource model = resourceStore.findById(id, resourceServer.getId());
Resource model = resourceStore.findById(resourceServer, id);
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -252,23 +252,23 @@ public class ResourceSetService {
PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
Set<Policy> policies = new HashSet<>();
policies.addAll(policyStore.findByResource(model.getId(), resourceServer.getId()));
policies.addAll(policyStore.findByResource(resourceServer, model));
if (model.getType() != null) {
policies.addAll(policyStore.findByResourceType(model.getType(), resourceServer.getId()));
policies.addAll(policyStore.findByResourceType(resourceServer, model.getType()));
Map<Resource.FilterOption, String[]> resourceFilter = new EnumMap<>(Resource.FilterOption.class);
resourceFilter.put(Resource.FilterOption.OWNER, new String[]{resourceServer.getId()});
resourceFilter.put(Resource.FilterOption.OWNER, new String[]{resourceServer.getClientId()});
resourceFilter.put(Resource.FilterOption.TYPE, new String[]{model.getType()});
for (Resource resourceType : resourceStore.findByResourceServer(resourceFilter, resourceServer.getId(), -1, -1)) {
policies.addAll(policyStore.findByResource(resourceType.getId(), resourceServer.getId()));
for (Resource resourceType : resourceStore.findByResourceServer(resourceServer, resourceFilter, null, null)) {
policies.addAll(policyStore.findByResource(resourceServer, resourceType));
}
}
policies.addAll(policyStore.findByScopeIds(model.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toList()), id, resourceServer.getId()));
policies.addAll(policyStore.findByScopeIds(model.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toList()), null, resourceServer.getId()));
policies.addAll(policyStore.findByScopes(resourceServer, model, model.getScopes()));
policies.addAll(policyStore.findByScopes(resourceServer, null, model.getScopes()));
List<PolicyRepresentation> representation = new ArrayList<>();
@ -296,7 +296,7 @@ public class ResourceSetService {
public Response getAttributes(@PathParam("id") String id) {
requireView();
StoreFactory storeFactory = authorization.getStoreFactory();
Resource model = storeFactory.getResourceStore().findById(id, resourceServer.getId());
Resource model = storeFactory.getResourceStore().findById(resourceServer, id);
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -317,13 +317,13 @@ public class ResourceSetService {
return Response.status(Status.BAD_REQUEST).build();
}
Resource model = storeFactory.getResourceStore().findByName(name, this.resourceServer.getId());
Resource model = storeFactory.getResourceStore().findByName(this.resourceServer, name);
if (model == null) {
return Response.status(Status.NO_CONTENT).build();
}
return Response.ok(toRepresentation(model, this.resourceServer.getId(), authorization)).build();
return Response.ok(toRepresentation(model, this.resourceServer, authorization)).build();
}
@GET
@ -340,7 +340,7 @@ public class ResourceSetService {
@QueryParam("deep") Boolean deep,
@QueryParam("first") Integer firstResult,
@QueryParam("max") Integer maxResult) {
return find(id, name, uri, owner, type, scope, matchingUri, exactName, deep, firstResult, maxResult, (BiFunction<Resource, Boolean, ResourceRepresentation>) (resource, deep1) -> toRepresentation(resource, resourceServer.getId(), authorization, deep1));
return find(id, name, uri, owner, type, scope, matchingUri, exactName, deep, firstResult, maxResult, (BiFunction<Resource, Boolean, ResourceRepresentation>) (resource, deep1) -> toRepresentation(resource, resourceServer, authorization, deep1));
}
public Response find(@QueryParam("_id") String id,
@ -403,7 +403,7 @@ public class ResourceSetService {
scopeFilter.put(Scope.FilterOption.NAME, new String[] {scope});
List<Scope> scopes = authorization.getStoreFactory().getScopeStore().findByResourceServer(scopeFilter, resourceServer.getId(), -1, -1);
List<Scope> scopes = authorization.getStoreFactory().getScopeStore().findByResourceServer(resourceServer, scopeFilter, null, null);
if (scopes.isEmpty()) {
return Response.ok(Collections.emptyList()).build();
@ -412,15 +412,15 @@ public class ResourceSetService {
search.put(Resource.FilterOption.SCOPE_ID, scopes.stream().map(Scope::getId).toArray(String[]::new));
}
List<Resource> resources = storeFactory.getResourceStore().findByResourceServer(search, this.resourceServer.getId(), firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS);
List<Resource> resources = storeFactory.getResourceStore().findByResourceServer(this.resourceServer, search, firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS);
if (matchingUri != null && matchingUri && resources.isEmpty()) {
Map<Resource.FilterOption, String[]> attributes = new EnumMap<>(Resource.FilterOption.class);
attributes.put(Resource.FilterOption.URI_NOT_NULL, new String[] {"true"});
attributes.put(Resource.FilterOption.OWNER, new String[] {resourceServer.getId()});
attributes.put(Resource.FilterOption.OWNER, new String[] {resourceServer.getClientId()});
List<Resource> serverResources = storeFactory.getResourceStore().findByResourceServer(attributes, this.resourceServer.getId(), firstResult != null ? firstResult : -1, maxResult != null ? maxResult : -1);
List<Resource> serverResources = storeFactory.getResourceStore().findByResourceServer(this.resourceServer, attributes, firstResult != null ? firstResult : -1, maxResult != null ? maxResult : -1);
PathMatcher<Map.Entry<String, Resource>> pathMatcher = new PathMatcher<Map.Entry<String, Resource>>() {
@Override

View file

@ -50,6 +50,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
@ -100,7 +101,7 @@ public class ScopeService {
this.auth.realm().requireManageAuthorization();
scope.setId(id);
StoreFactory storeFactory = authorization.getStoreFactory();
Scope model = storeFactory.getScopeStore().findById(scope.getId(), resourceServer.getId());
Scope model = storeFactory.getScopeStore().findById(resourceServer, scope.getId());
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -118,20 +119,19 @@ public class ScopeService {
public Response delete(@PathParam("id") String id) {
this.auth.realm().requireManageAuthorization();
StoreFactory storeFactory = authorization.getStoreFactory();
List<Resource> resources = storeFactory.getResourceStore().findByScope(Arrays.asList(id), resourceServer.getId());
if (!resources.isEmpty()) {
return ErrorResponse.error("Scopes can not be removed while associated with resources.", Status.BAD_REQUEST);
}
Scope scope = storeFactory.getScopeStore().findById(id, resourceServer.getId());
Scope scope = storeFactory.getScopeStore().findById(resourceServer, id);
if (scope == null) {
return Response.status(Status.NOT_FOUND).build();
}
List<Resource> resources = storeFactory.getResourceStore().findByScopes(resourceServer, Collections.singleton(scope));
if (!resources.isEmpty()) {
return ErrorResponse.error("Scopes can not be removed while associated with resources.", Status.BAD_REQUEST);
}
PolicyStore policyStore = storeFactory.getPolicyStore();
List<Policy> policies = policyStore.findByScopeIds(Arrays.asList(scope.getId()), resourceServer.getId());
List<Policy> policies = policyStore.findByScopes(resourceServer, Collections.singletonList(scope));
for (Policy policyModel : policies) {
if (policyModel.getScopes().size() == 1) {
@ -154,7 +154,7 @@ public class ScopeService {
@Produces(MediaType.APPLICATION_JSON)
public Response findById(@PathParam("id") String id) {
this.auth.realm().requireViewAuthorization();
Scope model = this.authorization.getStoreFactory().getScopeStore().findById(id, resourceServer.getId());
Scope model = this.authorization.getStoreFactory().getScopeStore().findById(resourceServer, id);
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -170,13 +170,13 @@ public class ScopeService {
public Response getResources(@PathParam("id") String id) {
this.auth.realm().requireViewAuthorization();
StoreFactory storeFactory = this.authorization.getStoreFactory();
Scope model = storeFactory.getScopeStore().findById(id, resourceServer.getId());
Scope model = storeFactory.getScopeStore().findById(resourceServer, id);
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok(storeFactory.getResourceStore().findByScope(Arrays.asList(model.getId()), resourceServer.getId()).stream().map(resource -> {
return Response.ok(storeFactory.getResourceStore().findByScopes(resourceServer, Collections.singleton(model)).stream().map(resource -> {
ResourceRepresentation representation = new ResourceRepresentation();
representation.setId(resource.getId());
@ -193,7 +193,7 @@ public class ScopeService {
public Response getPermissions(@PathParam("id") String id) {
this.auth.realm().requireViewAuthorization();
StoreFactory storeFactory = this.authorization.getStoreFactory();
Scope model = storeFactory.getScopeStore().findById(id, resourceServer.getId());
Scope model = storeFactory.getScopeStore().findById(resourceServer, id);
if (model == null) {
return Response.status(Status.NOT_FOUND).build();
@ -201,7 +201,7 @@ public class ScopeService {
PolicyStore policyStore = storeFactory.getPolicyStore();
return Response.ok(policyStore.findByScopeIds(Arrays.asList(model.getId()), resourceServer.getId()).stream().map(policy -> {
return Response.ok(policyStore.findByScopes(resourceServer, Collections.singletonList(model)).stream().map(policy -> {
PolicyRepresentation representation = new PolicyRepresentation();
representation.setId(policy.getId());
@ -224,7 +224,7 @@ public class ScopeService {
return Response.status(Status.BAD_REQUEST).build();
}
Scope model = storeFactory.getScopeStore().findByName(name, this.resourceServer.getId());
Scope model = storeFactory.getScopeStore().findByName(this.resourceServer, name);
if (model == null) {
return Response.status(Status.NO_CONTENT).build();
@ -253,7 +253,7 @@ public class ScopeService {
}
return Response.ok(
this.authorization.getStoreFactory().getScopeStore().findByResourceServer(search, this.resourceServer.getId(), firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS).stream()
this.authorization.getStoreFactory().getScopeStore().findByResourceServer(this.resourceServer, search, firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS).stream()
.map(scope -> toRepresentation(scope))
.collect(Collectors.toList()))
.build();

View file

@ -64,7 +64,7 @@ public class PolicyEvaluationResponseBuilder {
authorizationData.setPermissions(decision.results());
accessToken.setAuthorization(authorizationData);
ClientModel clientModel = authorization.getRealm().getClientById(resourceServer.getId());
ClientModel clientModel = authorization.getRealm().getClientById(resourceServer.getClientId());
if (!accessToken.hasAudience(clientModel.getClientId())) {
accessToken.audience(clientModel.getClientId());
@ -194,7 +194,7 @@ public class PolicyEvaluationResponseBuilder {
filters.put(PermissionTicket.FilterOption.POLICY_ID, policy.getId());
List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(filters, policy.getResourceServer().getId(), -1, 1);
List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(policy.getResourceServer(), filters, -1, 1);
if (!tickets.isEmpty()) {
KeycloakSession keycloakSession = authorization.getKeycloakSession();

View file

@ -224,7 +224,7 @@ public class AuthorizationTokenService {
if (isGranted(ticket, request, permissions)) {
AuthorizationProvider authorization = request.getAuthorization();
ClientModel targetClient = authorization.getRealm().getClientById(resourceServer.getId());
ClientModel targetClient = authorization.getRealm().getClientById(resourceServer.getClientId());
Metadata metadata = request.getMetadata();
String responseMode = metadata != null ? metadata.getResponseMode() : null;
@ -516,7 +516,7 @@ public class AuthorizationTokenService {
break;
}
Resource resource = resourceStore.findById(grantedPermission.getResourceId(), resourceServer.getId());
Resource resource = resourceStore.findById(resourceServer, grantedPermission.getResourceId());
if (resource != null) {
ResourcePermission permission = permissionsToEvaluate.get(resource.getId());
@ -540,7 +540,7 @@ public class AuthorizationTokenService {
}
for (String scopeName : grantedPermission.getScopes()) {
Scope scope = scopeStore.findByName(scopeName, resourceServer.getId());
Scope scope = scopeStore.findByName(resourceServer, scopeName);
if (scope != null) {
if (!permission.getScopes().contains(scope)) {
@ -561,7 +561,7 @@ public class AuthorizationTokenService {
Set<Scope> requestedScopesModel) {
AtomicBoolean processed = new AtomicBoolean();
resourceStore.findByScope(requestedScopesModel.stream().map(Scope::getId).collect(Collectors.toList()), resourceServer.getId(), resource -> {
resourceStore.findByScopes(resourceServer, requestedScopesModel, resource -> {
if (limit != null && limit.get() <= 0) {
return;
}
@ -600,7 +600,7 @@ public class AuthorizationTokenService {
Resource resource;
if (resourceId.indexOf('-') != -1) {
resource = resourceStore.findById(resourceId, resourceServer.getId());
resource = resourceStore.findById(resourceServer, resourceId);
} else {
resource = null;
}
@ -610,33 +610,33 @@ public class AuthorizationTokenService {
} else if (resourceId.startsWith("resource-type:")) {
// only resource types, no resource instances. resource types are owned by the resource server
String resourceType = resourceId.substring("resource-type:".length());
resourceStore.findByType(resourceType, resourceServer.getId(), resourceServer.getId(),
resourceStore.findByType(resourceServer, resourceType, resourceServer.getClientId(),
resource1 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource1));
} else if (resourceId.startsWith("resource-type-any:")) {
// any resource with a given type
String resourceType = resourceId.substring("resource-type-any:".length());
resourceStore.findByType(resourceType, null, resourceServer.getId(),
resourceStore.findByType(resourceServer, resourceType, null,
resource12 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource12));
} else if (resourceId.startsWith("resource-type-instance:")) {
// only resource instances with a given type
String resourceType = resourceId.substring("resource-type-instance:".length());
resourceStore.findByTypeInstance(resourceType, resourceServer.getId(),
resourceStore.findByTypeInstance(resourceServer, resourceType,
resource13 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource13));
} else if (resourceId.startsWith("resource-type-owner:")) {
// only resources where the current identity is the owner
String resourceType = resourceId.substring("resource-type-owner:".length());
resourceStore.findByType(resourceType, identity.getId(), resourceServer.getId(),
resourceStore.findByType(resourceServer, resourceType, identity.getId(),
resource14 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource14));
} else {
Resource ownerResource = resourceStore.findByName(resourceId, identity.getId(), resourceServer.getId());
Resource ownerResource = resourceStore.findByName(resourceServer, resourceId, identity.getId());
if (ownerResource != null) {
permission.setResourceId(ownerResource.getId());
addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, ownerResource);
}
if (!identity.isResourceServer() || !identity.getId().equals(resourceServer.getId())) {
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().findGranted(resourceId, identity.getId(), resourceServer.getId());
if (!identity.isResourceServer() || !identity.getId().equals(resourceServer.getClientId())) {
List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().findGranted(resourceServer, resourceId, identity.getId());
if (!tickets.isEmpty()) {
List<Scope> scopes = new ArrayList<>();
@ -656,7 +656,7 @@ public class AuthorizationTokenService {
resourcePermission.setGranted(true);
}
Resource serverResource = resourceStore.findByName(resourceId, resourceServer.getId());
Resource serverResource = resourceStore.findByName(resourceServer, resourceId);
if (serverResource != null) {
permission.setResourceId(serverResource.getId());
@ -685,7 +685,7 @@ public class AuthorizationTokenService {
requestedScopes.addAll(Arrays.asList(clientAdditionalScopes.split(" ")));
}
Set<Scope> requestedScopesModel = requestedScopes.stream().map(s -> scopeStore.findByName(s, resourceServer.getId())).filter(
Set<Scope> requestedScopesModel = requestedScopes.stream().map(s -> scopeStore.findByName(resourceServer, s)).filter(
Objects::nonNull).collect(Collectors.toSet());
if (!requestedScopes.isEmpty() && requestedScopesModel.isEmpty()) {

View file

@ -73,7 +73,7 @@ public class ProtectionService {
private AdminEventBuilder createAdminEventBuilder(KeycloakIdentity identity, ResourceServer resourceServer) {
RealmModel realm = authorization.getRealm();
ClientModel client = realm.getClientById(resourceServer.getId());
ClientModel client = realm.getClientById(resourceServer.getClientId());
KeycloakSession keycloakSession = authorization.getKeycloakSession();
UserModel serviceAccount = keycloakSession.users().getServiceAccount(client);
AdminEventBuilder adminEvent = new AdminEventBuilder(realm, new AdminAuth(realm, identity.getAccessToken(), serviceAccount, client), keycloakSession, clientConnection);
@ -118,7 +118,7 @@ public class ProtectionService {
ResourceServer resourceServer = getResourceServer(identity);
KeycloakSession keycloakSession = authorization.getKeycloakSession();
RealmModel realm = keycloakSession.getContext().getRealm();
ClientModel client = realm.getClientById(resourceServer.getId());
ClientModel client = realm.getClientById(resourceServer.getClientId());
if (checkProtectionScope) {
if (!identity.hasClientRole(client.getClientId(), "uma_protection")) {

View file

@ -74,19 +74,19 @@ public class AbstractPermissionService {
throw new ErrorResponseException("invalid_resource_id", "Resource id or name not provided.", Response.Status.BAD_REQUEST);
}
} else {
Resource resource = resourceStore.findById(resourceSetId, resourceServer.getId());
Resource resource = resourceStore.findById(resourceServer, resourceSetId);
if (resource != null) {
resources.add(resource);
} else {
Resource userResource = resourceStore.findByName(resourceSetId, identity.getId(), this.resourceServer.getId());
Resource userResource = resourceStore.findByName(this.resourceServer, resourceSetId, identity.getId());
if (userResource != null) {
resources.add(userResource);
}
if (!identity.isResourceServer()) {
Resource serverResource = resourceStore.findByName(resourceSetId, this.resourceServer.getId());
Resource serverResource = resourceStore.findByName(this.resourceServer, resourceSetId);
if (serverResource != null) {
resources.add(serverResource);
@ -127,13 +127,13 @@ public class AbstractPermissionService {
scope = resource.getScopes().stream().filter(scope1 -> scope1.getName().equals(scopeName)).findFirst().orElse(null);
if (scope == null && resource.getType() != null) {
scope = resourceStore.findByType(resource.getType(), resourceServer.getId()).stream()
.filter(baseResource -> baseResource.getOwner().equals(resource.getResourceServer()))
scope = resourceStore.findByType(resourceServer, resource.getType()).stream()
.filter(baseResource -> baseResource.getOwner().equals(resourceServer.getClientId()))
.flatMap(resource1 -> resource1.getScopes().stream())
.filter(baseScope -> baseScope.getName().equals(scopeName)).findFirst().orElse(null);
}
} else {
scope = authorization.getStoreFactory().getScopeStore().findByName(scopeName, resourceServer.getId());
scope = authorization.getStoreFactory().getScopeStore().findByName(resourceServer, scopeName);
}
if (scope == null) {

View file

@ -83,7 +83,7 @@ public class PermissionTicketService {
throw new ErrorResponseException("invalid_permission", "created permissions should have requester or requesterName", Response.Status.BAD_REQUEST);
ResourceStore rstore = this.authorization.getStoreFactory().getResourceStore();
Resource resource = rstore.findById(representation.getResource(), resourceServer.getId());
Resource resource = rstore.findById(resourceServer, representation.getResource());
if (resource == null ) throw new ErrorResponseException("invalid_resource_id", "Resource set with id [" + representation.getResource() + "] does not exists in this server.", Response.Status.BAD_REQUEST);
if (!resource.getOwner().equals(this.identity.getId()))
@ -102,9 +102,9 @@ public class PermissionTicketService {
ScopeStore sstore = this.authorization.getStoreFactory().getScopeStore();
if(representation.getScopeName() != null)
scope = sstore.findByName(representation.getScopeName(), resourceServer.getId());
scope = sstore.findByName(resourceServer, representation.getScopeName());
else
scope = sstore.findById(representation.getScope(), resourceServer.getId());
scope = sstore.findById(resourceServer, representation.getScope());
if (scope == null && representation.getScope() !=null )
throw new ErrorResponseException("invalid_scope", "Scope [" + representation.getScope() + "] is invalid", Response.Status.BAD_REQUEST);
@ -121,10 +121,10 @@ public class PermissionTicketService {
attributes.put(PermissionTicket.FilterOption.SCOPE_ID, scope.getId());
attributes.put(PermissionTicket.FilterOption.REQUESTER, user.getId());
if (!ticketStore.find(attributes, resourceServer.getId(), -1, -1).isEmpty())
if (!ticketStore.find(resourceServer, attributes, null, null).isEmpty())
throw new ErrorResponseException("invalid_permission", "Permission already exists", Response.Status.BAD_REQUEST);
PermissionTicket ticket = ticketStore.create(resource.getId(), scope.getId(), user.getId(), resourceServer);
PermissionTicket ticket = ticketStore.create(resourceServer, resource, scope, user.getId());
if(representation.isGranted())
ticket.setGrantedTimestamp(java.lang.System.currentTimeMillis());
representation = ModelToRepresentation.toRepresentation(ticket, authorization);
@ -139,7 +139,7 @@ public class PermissionTicketService {
}
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
PermissionTicket ticket = ticketStore.findById(representation.getId(), resourceServer.getId());
PermissionTicket ticket = ticketStore.findById(resourceServer, representation.getId());
if (ticket == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "invalid_ticket", Response.Status.BAD_REQUEST);
@ -148,7 +148,7 @@ public class PermissionTicketService {
if (!ticket.getOwner().equals(this.identity.getId()) && !this.identity.isResourceServer())
throw new ErrorResponseException("not_authorised", "permissions for [" + representation.getResource() + "] can be updated only by the owner or by the resource server", Response.Status.FORBIDDEN);
RepresentationToModel.toModel(representation, resourceServer.getId(), authorization);
RepresentationToModel.toModel(representation, resourceServer, authorization);
return Response.noContent().build();
}
@ -163,7 +163,7 @@ public class PermissionTicketService {
}
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
PermissionTicket ticket = ticketStore.findById(id, resourceServer.getId());
PermissionTicket ticket = ticketStore.findById(resourceServer, id);
if (ticket == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "invalid_ticket", Response.Status.BAD_REQUEST);
@ -192,7 +192,7 @@ public class PermissionTicketService {
Map<PermissionTicket.FilterOption, String> filters = getFilters(storeFactory, resourceId, scopeId, owner, requester, granted);
return Response.ok().entity(permissionTicketStore.find(filters, resourceServer.getId(), firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS)
return Response.ok().entity(permissionTicketStore.find(resourceServer, filters, firstResult != null ? firstResult : -1, maxResult != null ? maxResult : Constants.DEFAULT_MAX_RESULTS)
.stream()
.map(permissionTicket -> ModelToRepresentation.toRepresentation(permissionTicket, authorization, returnNames == null ? false : returnNames))
.collect(Collectors.toList()))
@ -211,7 +211,7 @@ public class PermissionTicketService {
StoreFactory storeFactory = authorization.getStoreFactory();
PermissionTicketStore permissionTicketStore = storeFactory.getPermissionTicketStore();
Map<PermissionTicket.FilterOption, String> filters = getFilters(storeFactory, resourceId, scopeId, owner, requester, granted);
long count = permissionTicketStore.count(filters, resourceServer.getId());
long count = permissionTicketStore.count(resourceServer, filters);
return Response.ok().entity(count).build();
}
@ -230,10 +230,10 @@ public class PermissionTicketService {
if (scopeId != null) {
ScopeStore scopeStore = storeFactory.getScopeStore();
Scope scope = scopeStore.findById(scopeId, resourceServer.getId());
Scope scope = scopeStore.findById(resourceServer, scopeId);
if (scope == null) {
scope = scopeStore.findByName(scopeId, resourceServer.getId());
scope = scopeStore.findByName(resourceServer, scopeId);
}
filters.put(PermissionTicket.FilterOption.SCOPE_ID, scope != null ? scope.getId() : scopeId);

View file

@ -132,7 +132,7 @@ public class UserManagedPermissionService {
}
private Policy getPolicy(@PathParam("policyId") String policyId) {
Policy existing = authorization.getStoreFactory().getPolicyStore().findById(policyId, resourceServer.getId());
Policy existing = authorization.getStoreFactory().getPolicyStore().findById(resourceServer, policyId);
if (existing == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Policy with [" + policyId + "] does not exist", Status.NOT_FOUND);
@ -143,7 +143,7 @@ public class UserManagedPermissionService {
private void checkRequest(String resourceId, UmaPermissionRepresentation representation) {
ResourceStore resourceStore = this.authorization.getStoreFactory().getResourceStore();
Resource resource = resourceStore.findById(resourceId, resourceServer.getId());
Resource resource = resourceStore.findById(resourceServer, resourceId);
if (resource == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Resource [" + resourceId + "] cannot be found", Response.Status.BAD_REQUEST);

View file

@ -309,11 +309,11 @@ public class ExportUtils {
representation.setName(null);
representation.setClientId(null);
List<ResourceRepresentation> resources = storeFactory.getResourceStore().findByResourceServer(settingsModel.getId())
List<ResourceRepresentation> resources = storeFactory.getResourceStore().findByResourceServer(settingsModel)
.stream().map(resource -> {
ResourceRepresentation rep = toRepresentation(resource, settingsModel.getId(), authorization);
ResourceRepresentation rep = toRepresentation(resource, settingsModel, authorization);
if (rep.getOwner().getId().equals(settingsModel.getId())) {
if (rep.getOwner().getId().equals(settingsModel.getClientId())) {
rep.setOwner((ResourceOwnerRepresentation) null);
} else {
rep.getOwner().setId(null);
@ -331,16 +331,16 @@ public class ExportUtils {
List<PolicyRepresentation> policies = new ArrayList<>();
PolicyStore policyStore = storeFactory.getPolicyStore();
policies.addAll(policyStore.findByResourceServer(settingsModel.getId())
policies.addAll(policyStore.findByResourceServer(settingsModel)
.stream().filter(policy -> !policy.getType().equals("resource") && !policy.getType().equals("scope") && policy.getOwner() == null)
.map(policy -> createPolicyRepresentation(authorization, policy)).collect(Collectors.toList()));
policies.addAll(policyStore.findByResourceServer(settingsModel.getId())
policies.addAll(policyStore.findByResourceServer(settingsModel)
.stream().filter(policy -> (policy.getType().equals("resource") || policy.getType().equals("scope") && policy.getOwner() == null))
.map(policy -> createPolicyRepresentation(authorization, policy)).collect(Collectors.toList()));
representation.setPolicies(policies);
List<ScopeRepresentation> scopes = storeFactory.getScopeStore().findByResourceServer(settingsModel.getId()).stream().map(scope -> {
List<ScopeRepresentation> scopes = storeFactory.getScopeStore().findByResourceServer(settingsModel).stream().map(scope -> {
ScopeRepresentation rep = toRepresentation(scope);
rep.setPolicies(null);

View file

@ -34,6 +34,7 @@ import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PermissionTicketStore;
import org.keycloak.common.util.Time;
@ -68,7 +69,7 @@ public class AuthorizationBean {
List<String> pathParameters = uriInfo.getPathParameters().get("resource_id");
if (pathParameters != null && !pathParameters.isEmpty()) {
Resource resource = authorization.getStoreFactory().getResourceStore().findById(pathParameters.get(0), null);
Resource resource = authorization.getStoreFactory().getResourceStore().findById(null, pathParameters.get(0));
if (resource != null && !resource.getOwner().equals(user.getId())) {
throw new RuntimeException("User [" + user.getUsername() + "] can not access resource [" + resource.getId() + "]");
@ -104,7 +105,7 @@ public class AuthorizationBean {
public List<ResourceBean> getResources() {
if (resources == null) {
resources = authorization.getStoreFactory().getResourceStore().findByOwner(user.getId(), null).stream()
resources = authorization.getStoreFactory().getResourceStore().findByOwner(null, user.getId()).stream()
.filter(Resource::isOwnerManagedAccess)
.map(ResourceBean::new)
.collect(Collectors.toList());
@ -121,7 +122,7 @@ public class AuthorizationBean {
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
userSharedResources = toResourceRepresentation(ticketStore.find(filters, null, -1, -1));
userSharedResources = toResourceRepresentation(ticketStore.find(null, filters, null, null));
}
return userSharedResources;
}
@ -139,7 +140,7 @@ public class AuthorizationBean {
}
private ResourceBean getResource(String id) {
return new ResourceBean(authorization.getStoreFactory().getResourceStore().findById(id, null));
return new ResourceBean(authorization.getStoreFactory().getResourceStore().findById(null, id));
}
public static class RequesterBean {
@ -235,7 +236,8 @@ public class AuthorizationBean {
public ResourceBean(Resource resource) {
RealmModel realm = authorization.getRealm();
resourceServer = new ResourceServerBean(realm.getClientById(resource.getResourceServer()));
ResourceServer resourceServerModel = resource.getResourceServer();
resourceServer = new ResourceServerBean(realm.getClientById(resourceServerModel.getClientId()), resourceServerModel);
this.resource = resource;
userOwner = authorization.getKeycloakSession().users().getUserById(realm, resource.getOwner());
if (userOwner == null) {
@ -304,7 +306,7 @@ public class AuthorizationBean {
filters.put(Policy.FilterOption.OWNER, new String[] {getClientOwner().getId()});
}
List<Policy> policies = authorization.getStoreFactory().getPolicyStore().findByResourceServer(filters, getResourceServer().getId(), -1, -1);
List<Policy> policies = authorization.getStoreFactory().getPolicyStore().findByResourceServer(getResourceServer().getResourceServerModel(), filters, null, null);
if (policies.isEmpty()) {
return Collections.emptyList();
@ -316,7 +318,7 @@ public class AuthorizationBean {
filters1.put(PermissionTicket.FilterOption.POLICY_ID, policy.getId());
return authorization.getStoreFactory().getPermissionTicketStore().find(filters1, resourceServer.getId(), -1, 1)
return authorization.getStoreFactory().getPermissionTicketStore().find(resourceServer.getResourceServerModel(), filters1, -1, 1)
.isEmpty();
})
.map(ManagedPermissionBean::new).collect(Collectors.toList());
@ -368,19 +370,21 @@ public class AuthorizationBean {
}
private List<PermissionTicket> findPermissions(Map<PermissionTicket.FilterOption, String> filters) {
return authorization.getStoreFactory().getPermissionTicketStore().find(filters, null, -1, -1);
return authorization.getStoreFactory().getPermissionTicketStore().find(null, filters, null, null);
}
public class ResourceServerBean {
private ClientModel clientModel;
private ResourceServer resourceServer;
public ResourceServerBean(ClientModel clientModel) {
public ResourceServerBean(ClientModel clientModel, ResourceServer resourceServer) {
this.clientModel = clientModel;
this.resourceServer = resourceServer;
}
public String getId() {
return clientModel.getId();
return resourceServer.getId();
}
public String getName() {
@ -410,6 +414,10 @@ public class AuthorizationBean {
public String getBaseUri() {
return ResolveRelative.resolveRelativeUri(session, clientModel.getRootUrl(), clientModel.getBaseUrl());
}
public ResourceServer getResourceServerModel() {
return resourceServer;
}
}
public class ManagedPermissionBean {

View file

@ -25,6 +25,7 @@ import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.store.PermissionTicketStore;
import org.keycloak.authorization.store.PolicyStore;
import org.keycloak.authorization.store.ScopeStore;
import org.keycloak.common.Profile;
import org.keycloak.common.util.Base64Url;
import org.keycloak.common.util.Time;
@ -110,6 +111,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
@ -760,7 +762,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
Resource resource = authorization.getStoreFactory().getResourceStore().findById(resourceId, null);
Resource resource = authorization.getStoreFactory().getResourceStore().findById(null, resourceId);
if (resource == null) {
return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
@ -780,13 +782,14 @@ public class AccountFormService extends AbstractSecuredLocalService {
List<String> ids = new ArrayList<>(Arrays.asList(permissionId));
Iterator<String> iterator = ids.iterator();
PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
ResourceServer resourceServer = authorization.getStoreFactory().getResourceServerStore().findByClient(client);
Policy policy = null;
while (iterator.hasNext()) {
String id = iterator.next();
if (!id.contains(":")) {
policy = policyStore.findById(id, client.getId());
policy = policyStore.findById(resourceServer, id);
iterator.remove();
break;
}
@ -800,7 +803,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
}
} else {
for (String id : ids) {
scopesToKeep.add(authorization.getStoreFactory().getScopeStore().findById(id.split(":")[1], client.getId()));
scopesToKeep.add(authorization.getStoreFactory().getScopeStore().findById(resourceServer, id.split(":")[1]));
}
for (Scope scope : policy.getScopes()) {
@ -829,7 +832,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.FALSE.toString());
}
List<PermissionTicket> tickets = ticketStore.find(filters, resource.getResourceServer(), -1, -1);
List<PermissionTicket> tickets = ticketStore.find(resource.getResourceServer(), filters, null, null);
Iterator<PermissionTicket> iterator = tickets.iterator();
while (iterator.hasNext()) {
@ -884,8 +887,9 @@ public class AccountFormService extends AbstractSecuredLocalService {
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
Resource resource = authorization.getStoreFactory().getResourceStore().findById(resourceId, null);
ResourceServer resourceServer = authorization.getStoreFactory().getResourceServerStore().findById(resource.getResourceServer());
ScopeStore scopeStore = authorization.getStoreFactory().getScopeStore();
Resource resource = authorization.getStoreFactory().getResourceStore().findById(null, resourceId);
ResourceServer resourceServer = resource.getResourceServer();
if (resource == null) {
return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
@ -918,38 +922,39 @@ public class AccountFormService extends AbstractSecuredLocalService {
filters.put(PermissionTicket.FilterOption.OWNER, auth.getUser().getId());
filters.put(PermissionTicket.FilterOption.REQUESTER, user.getId());
List<PermissionTicket> tickets = ticketStore.find(filters, resource.getResourceServer(), -1, -1);
List<PermissionTicket> tickets = ticketStore.find(resourceServer, filters, null, null);
final String userId = user.getId();
if (tickets.isEmpty()) {
if (scopes != null && scopes.length > 0) {
for (String scope : scopes) {
PermissionTicket ticket = ticketStore.create(resourceId, scope, user.getId(), resourceServer);
for (String scopeId : scopes) {
Scope scope = scopeStore.findById(resourceServer, scopeId);
PermissionTicket ticket = ticketStore.create(resourceServer, resource, scope, userId);
ticket.setGrantedTimestamp(System.currentTimeMillis());
}
} else {
if (resource.getScopes().isEmpty()) {
PermissionTicket ticket = ticketStore.create(resourceId, null, user.getId(), resourceServer);
PermissionTicket ticket = ticketStore.create(resourceServer, resource, null, userId);
ticket.setGrantedTimestamp(System.currentTimeMillis());
} else {
for (Scope scope : resource.getScopes()) {
PermissionTicket ticket = ticketStore.create(resourceId, scope.getId(), user.getId(), resourceServer);
PermissionTicket ticket = ticketStore.create(resourceServer, resource, scope, userId);
ticket.setGrantedTimestamp(System.currentTimeMillis());
}
}
}
} else if (scopes != null && scopes.length > 0) {
List<String> grantScopes = new ArrayList<>(Arrays.asList(scopes));
Set<String> alreadyGrantedScopes = tickets.stream()
.map(PermissionTicket::getScope)
.map(Scope::getId)
.collect(Collectors.toSet());
for (PermissionTicket ticket : tickets) {
Scope scope = ticket.getScope();
grantScopes.removeIf(alreadyGrantedScopes::contains);
if (scope != null) {
grantScopes.remove(scope.getId());
}
}
for (String grantScope : grantScopes) {
PermissionTicket ticket = ticketStore.create(resourceId, grantScope, user.getId(), resourceServer);
for (String scopeId : grantScopes) {
Scope scope = scopeStore.findById(resourceServer, scopeId);
PermissionTicket ticket = ticketStore.create(resourceServer, resource, scope, userId);
ticket.setGrantedTimestamp(System.currentTimeMillis());
}
}
@ -978,7 +983,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
}
for (String resourceId : resourceIds) {
Resource resource = authorization.getStoreFactory().getResourceStore().findById(resourceId, null);
Resource resource = authorization.getStoreFactory().getResourceStore().findById(null, resourceId);
if (resource == null) {
return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
@ -995,7 +1000,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.FALSE.toString());
}
for (PermissionTicket ticket : ticketStore.find(filters, resource.getResourceServer(), -1, -1)) {
for (PermissionTicket ticket : ticketStore.find(resource.getResourceServer(), filters, null, null)) {
ticketStore.delete(ticket.getId());
}
}

View file

@ -28,6 +28,7 @@ import java.util.stream.Collectors;
import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.store.PermissionTicketStore;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.authorization.store.ScopeStore;
@ -82,7 +83,8 @@ public abstract class AbstractResourceService {
setScopes(resource.getScopes().stream().map(Scope::new).collect(Collectors.toSet()));
this.client = new Client(provider.getRealm().getClientById(resource.getResourceServer()));
ResourceServer resourceServer = resource.getResourceServer();
this.client = new Client(provider.getRealm().getClientById(resourceServer.getClientId()));
}
Resource(org.keycloak.authorization.model.Resource resource, AuthorizationProvider provider) {

View file

@ -58,7 +58,7 @@ public class ResourceService extends AbstractResourceService {
Auth auth, HttpRequest request) {
super(session, user, auth, request);
this.resource = resource;
this.resourceServer = provider.getStoreFactory().getResourceServerStore().findByClient(provider.getRealm().getClientById(resource.getResourceServer()));
this.resourceServer = resource.getResourceServer();
}
/**
@ -87,7 +87,7 @@ public class ResourceService extends AbstractResourceService {
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
filters.put(PermissionTicket.FilterOption.RESOURCE_ID, resource.getId());
Collection<ResourcePermission> resources = toPermissions(ticketStore.find(filters, null, -1, -1));
Collection<ResourcePermission> resources = toPermissions(ticketStore.find(null, filters, null, null));
Collection<Permission> permissions = Collections.EMPTY_LIST;
if (!resources.isEmpty()) {
@ -135,7 +135,7 @@ public class ResourceService extends AbstractResourceService {
filters.put(PermissionTicket.FilterOption.REQUESTER, user.getId());
List<PermissionTicket> tickets = ticketStore.find(filters, resource.getResourceServer(), -1, -1);
List<PermissionTicket> tickets = ticketStore.find(resource.getResourceServer(), filters, null, null);
// grants all requested permissions
if (tickets.isEmpty()) {
@ -196,7 +196,7 @@ public class ResourceService extends AbstractResourceService {
Map<String, Permission> requests = new HashMap<>();
for (PermissionTicket ticket : ticketStore.find(filters, null, -1, -1)) {
for (PermissionTicket ticket : ticketStore.find(null, filters, null, null)) {
requests.computeIfAbsent(ticket.getRequester(), requester -> new Permission(ticket, provider)).addScope(ticket.getScope().getName());
}
@ -205,15 +205,15 @@ public class ResourceService extends AbstractResourceService {
private void grantPermission(UserModel user, String scopeId) {
org.keycloak.authorization.model.Scope scope = getScope(scopeId, resourceServer);
PermissionTicket ticket = ticketStore.create(resource.getId(), scope.getId(), user.getId(), resourceServer);
PermissionTicket ticket = ticketStore.create(resourceServer, resource, scope, user.getId());
ticket.setGrantedTimestamp(Calendar.getInstance().getTimeInMillis());
}
private org.keycloak.authorization.model.Scope getScope(String scopeId, ResourceServer resourceServer) {
org.keycloak.authorization.model.Scope scope = scopeStore.findByName(scopeId, resourceServer.getId());
org.keycloak.authorization.model.Scope scope = scopeStore.findByName(resourceServer, scopeId);
if (scope == null) {
scope = scopeStore.findById(scopeId, resourceServer.getId());
scope = scopeStore.findById(resourceServer, scopeId);
}
return scope;

View file

@ -73,7 +73,7 @@ public class ResourcesService extends AbstractResourceService {
filters.put(org.keycloak.authorization.model.Resource.FilterOption.NAME, new String[] { name });
}
return queryResponse((f, m) -> resourceStore.findByResourceServer(filters, null, f, m).stream()
return queryResponse((f, m) -> resourceStore.findByResourceServer(null, filters, f, m).stream()
.map(resource -> new Resource(resource, user, provider)), first, max);
}
@ -123,7 +123,7 @@ public class ResourcesService extends AbstractResourceService {
filters.put(PermissionTicket.FilterOption.REQUESTER, user.getId());
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.FALSE.toString());
final List<PermissionTicket> permissionTickets = ticketStore.find(filters, null, -1, -1);
final List<PermissionTicket> permissionTickets = ticketStore.find(null, filters, null, null);
final List<ResourcePermission> resourceList = new ArrayList<>(permissionTickets.size());
for (PermissionTicket ticket : permissionTickets) {
@ -138,7 +138,7 @@ public class ResourcesService extends AbstractResourceService {
@Path("{id}")
public Object getResource(@PathParam("id") String id) {
org.keycloak.authorization.model.Resource resource = resourceStore.findById(id, null);
org.keycloak.authorization.model.Resource resource = resourceStore.findById(null, id);
if (resource == null) {
throw new NotFoundException("resource_not_found");
@ -167,9 +167,9 @@ public class ResourcesService extends AbstractResourceService {
filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
filters.put(PermissionTicket.FilterOption.RESOURCE_ID, resource.getId());
tickets = ticketStore.find(filters, null, -1, -1);
tickets = ticketStore.find(resource.getResourceServer(), filters, null, null);
} else {
tickets = ticketStore.findGranted(resource.getName(), user.getId(), null);
tickets = ticketStore.findGranted(resource.getResourceServer(), resource.getName(), user.getId());
}
for (PermissionTicket ticket : tickets) {

View file

@ -95,15 +95,15 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = root.findOrCreateResourceServer(client);
Scope manageScope = manageScope(server);
if (manageScope == null) {
manageScope = authz.getStoreFactory().getScopeStore().create(AdminPermissionManagement.MANAGE_SCOPE, server);
manageScope = authz.getStoreFactory().getScopeStore().create(server, AdminPermissionManagement.MANAGE_SCOPE);
}
Scope viewScope = viewScope(server);
if (viewScope == null) {
viewScope = authz.getStoreFactory().getScopeStore().create(AdminPermissionManagement.VIEW_SCOPE, server);
viewScope = authz.getStoreFactory().getScopeStore().create(server, AdminPermissionManagement.VIEW_SCOPE);
}
Scope mapRoleScope = mapRolesScope(server);
if (mapRoleScope == null) {
mapRoleScope = authz.getStoreFactory().getScopeStore().create(MAP_ROLES_SCOPE, server);
mapRoleScope = authz.getStoreFactory().getScopeStore().create(server, MAP_ROLES_SCOPE);
}
Scope mapRoleClientScope = root.initializeScope(MAP_ROLES_CLIENT_SCOPE, server);
Scope mapRoleCompositeScope = root.initializeScope(MAP_ROLES_COMPOSITE_SCOPE, server);
@ -111,9 +111,9 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
Scope exchangeToScope = root.initializeScope(TOKEN_EXCHANGE, server);
String resourceName = getResourceName(client);
Resource resource = authz.getStoreFactory().getResourceStore().findByName(resourceName, server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, resourceName);
if (resource == null) {
resource = authz.getStoreFactory().getResourceStore().create(resourceName, server, server.getId());
resource = authz.getStoreFactory().getResourceStore().create(server, resourceName, server.getClientId());
resource.setType("Client");
Set<Scope> scopeset = new HashSet<>();
scopeset.add(configureScope);
@ -126,44 +126,44 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
resource.updateScopes(scopeset);
}
String managePermissionName = getManagePermissionName(client);
Policy managePermission = authz.getStoreFactory().getPolicyStore().findByName(managePermissionName, server.getId());
Policy managePermission = authz.getStoreFactory().getPolicyStore().findByName(server, managePermissionName);
if (managePermission == null) {
Helper.addEmptyScopePermission(authz, server, managePermissionName, resource, manageScope);
}
String configurePermissionName = getConfigurePermissionName(client);
Policy configurePermission = authz.getStoreFactory().getPolicyStore().findByName(configurePermissionName, server.getId());
Policy configurePermission = authz.getStoreFactory().getPolicyStore().findByName(server, configurePermissionName);
if (configurePermission == null) {
Helper.addEmptyScopePermission(authz, server, configurePermissionName, resource, configureScope);
}
String viewPermissionName = getViewPermissionName(client);
Policy viewPermission = authz.getStoreFactory().getPolicyStore().findByName(viewPermissionName, server.getId());
Policy viewPermission = authz.getStoreFactory().getPolicyStore().findByName(server, viewPermissionName);
if (viewPermission == null) {
Helper.addEmptyScopePermission(authz, server, viewPermissionName, resource, viewScope);
}
String mapRolePermissionName = getMapRolesPermissionName(client);
Policy mapRolePermission = authz.getStoreFactory().getPolicyStore().findByName(mapRolePermissionName, server.getId());
Policy mapRolePermission = authz.getStoreFactory().getPolicyStore().findByName(server, mapRolePermissionName);
if (mapRolePermission == null) {
Helper.addEmptyScopePermission(authz, server, mapRolePermissionName, resource, mapRoleScope);
}
String mapRoleClientScopePermissionName = getMapRolesClientScopePermissionName(client);
Policy mapRoleClientScopePermission = authz.getStoreFactory().getPolicyStore().findByName(mapRoleClientScopePermissionName, server.getId());
Policy mapRoleClientScopePermission = authz.getStoreFactory().getPolicyStore().findByName(server, mapRoleClientScopePermissionName);
if (mapRoleClientScopePermission == null) {
Helper.addEmptyScopePermission(authz, server, mapRoleClientScopePermissionName, resource, mapRoleClientScope);
}
String mapRoleCompositePermissionName = getMapRolesCompositePermissionName(client);
Policy mapRoleCompositePermission = authz.getStoreFactory().getPolicyStore().findByName(mapRoleCompositePermissionName, server.getId());
Policy mapRoleCompositePermission = authz.getStoreFactory().getPolicyStore().findByName(server, mapRoleCompositePermissionName);
if (mapRoleCompositePermission == null) {
Helper.addEmptyScopePermission(authz, server, mapRoleCompositePermissionName, resource, mapRoleCompositeScope);
}
String exchangeToPermissionName = getExchangeToPermissionName(client);
Policy exchangeToPermission = authz.getStoreFactory().getPolicyStore().findByName(exchangeToPermissionName, server.getId());
Policy exchangeToPermission = authz.getStoreFactory().getPolicyStore().findByName(server, exchangeToPermissionName);
if (exchangeToPermission == null) {
Helper.addEmptyScopePermission(authz, server, exchangeToPermissionName, resource, exchangeToScope);
}
}
private void deletePolicy(String name, ResourceServer server) {
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(name, server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, name);
if (policy != null) {
authz.getStoreFactory().getPolicyStore().delete(policy.getId());
}
@ -180,7 +180,7 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
deletePolicy(getMapRolesCompositePermissionName(client), server);
deletePolicy(getConfigurePermissionName(client), server);
deletePolicy(getExchangeToPermissionName(client), server);
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));;
if (resource != null) authz.getStoreFactory().getResourceStore().delete(resource.getId());
}
@ -189,7 +189,7 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = resourceServer(client);
if (server == null) return false;
return authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId()) != null;
return authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client)) != null;
}
@Override
@ -204,22 +204,22 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
private Scope manageScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(AdminPermissionManagement.MANAGE_SCOPE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, AdminPermissionManagement.MANAGE_SCOPE);
}
private Scope exchangeToScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(TOKEN_EXCHANGE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, TOKEN_EXCHANGE);
}
private Scope configureScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(CONFIGURE_SCOPE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, CONFIGURE_SCOPE);
}
private Scope viewScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(AdminPermissionManagement.VIEW_SCOPE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, AdminPermissionManagement.VIEW_SCOPE);
}
private Scope mapRolesScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(MAP_ROLES_SCOPE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, MAP_ROLES_SCOPE);
}
@Override
@ -284,7 +284,7 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
public Resource resource(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));
if (resource == null) return null;
return resource;
}
@ -313,13 +313,13 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
return false;
}
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(to), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(to));
if (resource == null) {
logger.debug("No resource object set up for target client");
return false;
}
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getExchangeToPermissionName(to), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getExchangeToPermissionName(to));
if (policy == null) {
logger.debug("No permission object set up for target client");
return false;
@ -366,10 +366,10 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = resourceServer(client);
if (server == null) return false;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));
if (resource == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getManagePermissionName(client), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getManagePermissionName(client));
if (policy == null) {
return false;
}
@ -394,10 +394,10 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = resourceServer(client);
if (server == null) return false;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));
if (resource == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getConfigurePermissionName(client), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getConfigurePermissionName(client));
if (policy == null) {
return false;
}
@ -440,10 +440,10 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = resourceServer(client);
if (server == null) return false;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));
if (resource == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getViewPermissionName(client), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getViewPermissionName(client));
if (policy == null) {
return false;
}
@ -519,10 +519,10 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = resourceServer(client);
if (server == null) return false;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));
if (resource == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getMapRolesPermissionName(client), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getMapRolesPermissionName(client));
if (policy == null) {
return false;
}
@ -541,49 +541,49 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
public Policy exchangeToPermission(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getExchangeToPermissionName(client), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getExchangeToPermissionName(client));
}
@Override
public Policy mapRolesPermission(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getMapRolesPermissionName(client), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getMapRolesPermissionName(client));
}
@Override
public Policy mapRolesClientScopePermission(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getMapRolesClientScopePermissionName(client), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getMapRolesClientScopePermissionName(client));
}
@Override
public Policy mapRolesCompositePermission(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getMapRolesCompositePermissionName(client), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getMapRolesCompositePermissionName(client));
}
@Override
public Policy managePermission(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getManagePermissionName(client), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getManagePermissionName(client));
}
@Override
public Policy configurePermission(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getConfigurePermissionName(client), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getConfigurePermissionName(client));
}
@Override
public Policy viewPermission(ClientModel client) {
ResourceServer server = resourceServer(client);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getViewPermissionName(client), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getViewPermissionName(client));
}
@Override
@ -596,10 +596,10 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = resourceServer(client);
if (server == null) return false;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));
if (resource == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getMapRolesCompositePermissionName(client), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getMapRolesCompositePermissionName(client));
if (policy == null) {
return false;
}
@ -610,7 +610,7 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
return false;
}
Scope scope = authz.getStoreFactory().getScopeStore().findByName(MAP_ROLES_COMPOSITE_SCOPE, server.getId());
Scope scope = authz.getStoreFactory().getScopeStore().findByName(server, MAP_ROLES_COMPOSITE_SCOPE);
return root.evaluatePermission(resource, server, scope);
}
@Override
@ -618,10 +618,10 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
ResourceServer server = resourceServer(client);
if (server == null) return false;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(client), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(client));
if (resource == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getMapRolesClientScopePermissionName(client), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getMapRolesClientScopePermissionName(client));
if (policy == null) {
return false;
}
@ -632,7 +632,7 @@ class ClientPermissions implements ClientPermissionEvaluator, ClientPermissionM
return false;
}
Scope scope = authz.getStoreFactory().getScopeStore().findByName(MAP_ROLES_CLIENT_SCOPE, server.getId());
Scope scope = authz.getStoreFactory().getScopeStore().findByName(server, MAP_ROLES_CLIENT_SCOPE);
return root.evaluatePermission(resource, server, scope);
}

View file

@ -105,9 +105,9 @@ class GroupPermissions implements GroupPermissionEvaluator, GroupPermissionManag
Scope manageMembershipScope = root.initializeRealmScope(MANAGE_MEMBERSHIP_SCOPE);
String groupResourceName = getGroupResourceName(group);
Resource groupResource = resourceStore.findByName(groupResourceName, server.getId());
Resource groupResource = resourceStore.findByName(server, groupResourceName);
if (groupResource == null) {
groupResource = resourceStore.create(groupResourceName, server, server.getId());
groupResource = resourceStore.create(server, groupResourceName, server.getClientId());
Set<Scope> scopeset = new HashSet<>();
scopeset.add(manageScope);
scopeset.add(viewScope);
@ -118,27 +118,27 @@ class GroupPermissions implements GroupPermissionEvaluator, GroupPermissionManag
groupResource.setType("Group");
}
String managePermissionName = getManagePermissionGroup(group);
Policy managePermission = policyStore.findByName(managePermissionName, server.getId());
Policy managePermission = policyStore.findByName(server, managePermissionName);
if (managePermission == null) {
Helper.addEmptyScopePermission(authz, server, managePermissionName, groupResource, manageScope);
}
String viewPermissionName = getViewPermissionGroup(group);
Policy viewPermission = policyStore.findByName(viewPermissionName, server.getId());
Policy viewPermission = policyStore.findByName(server, viewPermissionName);
if (viewPermission == null) {
Helper.addEmptyScopePermission(authz, server, viewPermissionName, groupResource, viewScope);
}
String manageMembersPermissionName = getManageMembersPermissionGroup(group);
Policy manageMembersPermission = policyStore.findByName(manageMembersPermissionName, server.getId());
Policy manageMembersPermission = policyStore.findByName(server, manageMembersPermissionName);
if (manageMembersPermission == null) {
Helper.addEmptyScopePermission(authz, server, manageMembersPermissionName, groupResource, manageMembersScope);
}
String viewMembersPermissionName = getViewMembersPermissionGroup(group);
Policy viewMembersPermission = policyStore.findByName(viewMembersPermissionName, server.getId());
Policy viewMembersPermission = policyStore.findByName(server, viewMembersPermissionName);
if (viewMembersPermission == null) {
Helper.addEmptyScopePermission(authz, server, viewMembersPermissionName, groupResource, viewMembersScope);
}
String manageMembershipPermissionName = getManageMembershipPermissionGroup(group);
Policy manageMembershipPermission = policyStore.findByName(manageMembershipPermissionName, server.getId());
Policy manageMembershipPermission = policyStore.findByName(server, manageMembershipPermissionName);
if (manageMembershipPermission == null) {
Helper.addEmptyScopePermission(authz, server, manageMembershipPermissionName, groupResource, manageMembershipScope);
}
@ -162,7 +162,7 @@ class GroupPermissions implements GroupPermissionEvaluator, GroupPermissionManag
ResourceServer server = root.realmResourceServer();
if (server == null) return false;
return resourceStore.findByName(getGroupResourceName(group), server.getId()) != null;
return resourceStore.findByName(server, getGroupResourceName(group)) != null;
}
@Override
@ -178,42 +178,42 @@ class GroupPermissions implements GroupPermissionEvaluator, GroupPermissionManag
public Policy viewMembersPermission(GroupModel group) {
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
return policyStore.findByName(getViewMembersPermissionGroup(group), server.getId());
return policyStore.findByName(server, getViewMembersPermissionGroup(group));
}
@Override
public Policy manageMembersPermission(GroupModel group) {
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
return policyStore.findByName(getManageMembersPermissionGroup(group), server.getId());
return policyStore.findByName(server, getManageMembersPermissionGroup(group));
}
@Override
public Policy manageMembershipPermission(GroupModel group) {
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
return policyStore.findByName(getManageMembershipPermissionGroup(group), server.getId());
return policyStore.findByName(server, getManageMembershipPermissionGroup(group));
}
@Override
public Policy viewPermission(GroupModel group) {
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
return policyStore.findByName(getViewPermissionGroup(group), server.getId());
return policyStore.findByName(server, getViewPermissionGroup(group));
}
@Override
public Policy managePermission(GroupModel group) {
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
return policyStore.findByName(getManagePermissionGroup(group), server.getId());
return policyStore.findByName(server, getManagePermissionGroup(group));
}
@Override
public Resource resource(GroupModel group) {
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
Resource resource = resourceStore.findByName(getGroupResourceName(group), server.getId());
Resource resource = resourceStore.findByName(server, getGroupResourceName(group));
if (resource == null) return null;
return resource;
}
@ -325,7 +325,7 @@ class GroupPermissions implements GroupPermissionEvaluator, GroupPermissionManag
Set<String> granted = new HashSet<>();
resourceStore.findByType("Group", server.getId(), resource -> {
resourceStore.findByType(server, "Group", resource -> {
if (hasPermission(resource, null, VIEW_MEMBERS_SCOPE, MANAGE_MEMBERS_SCOPE)) {
granted.add(resource.getName().substring(RESOURCE_NAME_PREFIX.length()));
}
@ -400,7 +400,7 @@ class GroupPermissions implements GroupPermissionEvaluator, GroupPermissionManag
return false;
}
Resource resource = resourceStore.findByName(getGroupResourceName(group), server.getId());
Resource resource = resourceStore.findByName(server, getGroupResourceName(group));
if (resource == null) {
return false;
@ -437,7 +437,7 @@ class GroupPermissions implements GroupPermissionEvaluator, GroupPermissionManag
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
String groupResourceName = getGroupResourceName(group);
return resourceStore.findByName(groupResourceName, server.getId());
return resourceStore.findByName(server, groupResourceName);
}
private void deletePermissions(GroupModel group) {

View file

@ -46,7 +46,7 @@ class Helper {
representation.addScope(scope.getName());
representation.addPolicy(policy.getName());
return authz.getStoreFactory().getPolicyStore().create(representation, resourceServer);
return authz.getStoreFactory().getPolicyStore().create(resourceServer, representation);
}
public static Policy addEmptyScopePermission(AuthorizationProvider authz, ResourceServer resourceServer, String name, Resource resource, Scope scope) {
@ -58,7 +58,7 @@ class Helper {
representation.addResource(resource.getName());
representation.addScope(scope.getName());
return authz.getStoreFactory().getPolicyStore().create(representation, resourceServer);
return authz.getStoreFactory().getPolicyStore().create(resourceServer, representation);
}
public static Policy createRolePolicy(AuthorizationProvider authz, ResourceServer resourceServer, RoleModel role) {
@ -78,7 +78,7 @@ class Helper {
config.put("roles", roleValues);
representation.setConfig(config);
return authz.getStoreFactory().getPolicyStore().create(representation, resourceServer);
return authz.getStoreFactory().getPolicyStore().create(resourceServer, representation);
}
public static String getRolePolicyName(RoleModel role) {

View file

@ -73,23 +73,23 @@ class IdentityProviderPermissions implements IdentityProviderPermissionManageme
Scope exchangeToScope = root.initializeScope(TOKEN_EXCHANGE, server);
String resourceName = getResourceName(idp);
Resource resource = authz.getStoreFactory().getResourceStore().findByName(resourceName, server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, resourceName);
if (resource == null) {
resource = authz.getStoreFactory().getResourceStore().create(resourceName, server, server.getId());
resource = authz.getStoreFactory().getResourceStore().create(server, resourceName, server.getClientId());
resource.setType("IdentityProvider");
Set<Scope> scopeset = new HashSet<>();
scopeset.add(exchangeToScope);
resource.updateScopes(scopeset);
}
String exchangeToPermissionName = getExchangeToPermissionName(idp);
Policy exchangeToPermission = authz.getStoreFactory().getPolicyStore().findByName(exchangeToPermissionName, server.getId());
Policy exchangeToPermission = authz.getStoreFactory().getPolicyStore().findByName(server, exchangeToPermissionName);
if (exchangeToPermission == null) {
Helper.addEmptyScopePermission(authz, server, exchangeToPermissionName, resource, exchangeToScope);
}
}
private void deletePolicy(String name, ResourceServer server) {
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(name, server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, name);
if (policy != null) {
authz.getStoreFactory().getPolicyStore().delete(policy.getId());
}
@ -100,7 +100,7 @@ class IdentityProviderPermissions implements IdentityProviderPermissionManageme
ResourceServer server = root.initializeRealmResourceServer();
if (server == null) return;
deletePolicy(getExchangeToPermissionName(idp), server);
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(idp), server.getId());;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(idp));;
if (resource != null) authz.getStoreFactory().getResourceStore().delete(resource.getId());
}
@ -109,7 +109,7 @@ class IdentityProviderPermissions implements IdentityProviderPermissionManageme
ResourceServer server = root.initializeRealmResourceServer();
if (server == null) return false;
return authz.getStoreFactory().getResourceStore().findByName(getResourceName(idp), server.getId()) != null;
return authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(idp)) != null;
}
@Override
@ -124,14 +124,14 @@ class IdentityProviderPermissions implements IdentityProviderPermissionManageme
private Scope exchangeToScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(TOKEN_EXCHANGE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, TOKEN_EXCHANGE);
}
@Override
public Resource resource(IdentityProviderModel idp) {
ResourceServer server = root.initializeRealmResourceServer();
if (server == null) return null;
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(idp), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(idp));
if (resource == null) return null;
return resource;
}
@ -153,13 +153,13 @@ class IdentityProviderPermissions implements IdentityProviderPermissionManageme
return false;
}
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getResourceName(to), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getResourceName(to));
if (resource == null) {
logger.debug("No resource object set up for target idp");
return false;
}
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getExchangeToPermissionName(to), server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, getExchangeToPermissionName(to));
if (policy == null) {
logger.debug("No permission object set up for target idp");
return false;
@ -194,7 +194,7 @@ class IdentityProviderPermissions implements IdentityProviderPermissionManageme
public Policy exchangeToPermission(IdentityProviderModel idp) {
ResourceServer server = root.initializeRealmResourceServer();
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getExchangeToPermissionName(idp), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getExchangeToPermissionName(idp));
}
}

View file

@ -283,17 +283,17 @@ class MgmtPermissions implements AdminPermissionEvaluator, AdminPermissionManage
public Scope initializeRealmScope(String name) {
ResourceServer server = initializeRealmResourceServer();
Scope scope = authz.getStoreFactory().getScopeStore().findByName(name, server.getId());
Scope scope = authz.getStoreFactory().getScopeStore().findByName(server, name);
if (scope == null) {
scope = authz.getStoreFactory().getScopeStore().create(name, server);
scope = authz.getStoreFactory().getScopeStore().create(server, name);
}
return scope;
}
public Scope initializeScope(String name, ResourceServer server) {
Scope scope = authz.getStoreFactory().getScopeStore().findByName(name, server.getId());
Scope scope = authz.getStoreFactory().getScopeStore().findByName(server, name);
if (scope == null) {
scope = authz.getStoreFactory().getScopeStore().create(name, server);
scope = authz.getStoreFactory().getScopeStore().create(server, name);
}
return scope;
}
@ -316,7 +316,7 @@ class MgmtPermissions implements AdminPermissionEvaluator, AdminPermissionManage
public Scope realmScope(String scope) {
ResourceServer server = realmResourceServer();
if (server == null) return null;
return authz.getStoreFactory().getScopeStore().findByName(scope, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, scope);
}
public boolean evaluatePermission(Resource resource, ResourceServer resourceServer, Scope... scope) {

View file

@ -81,7 +81,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
policy = mapCompositePermission(role);
if (policy != null) authz.getStoreFactory().getPolicyStore().delete(policy.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(getRoleResourceName(role), server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, getRoleResourceName(role));
if (resource != null) authz.getStoreFactory().getResourceStore().delete(resource.getId());
}
@ -99,7 +99,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
public Policy mapRolePermission(RoleModel role) {
ResourceServer server = resourceServer(role);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getMapRolePermissionName(role), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getMapRolePermissionName(role));
}
@Override
@ -107,7 +107,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
ResourceServer server = resourceServer(role);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getMapCompositePermissionName(role), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getMapCompositePermissionName(role));
}
@Override
@ -115,7 +115,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
ResourceServer server = resourceServer(role);
if (server == null) return null;
return authz.getStoreFactory().getPolicyStore().findByName(getMapClientScopePermissionName(role), server.getId());
return authz.getStoreFactory().getPolicyStore().findByName(server, getMapClientScopePermissionName(role));
}
@Override
@ -123,7 +123,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
ResourceStore resourceStore = authz.getStoreFactory().getResourceStore();
ResourceServer server = resourceServer(role);
if (server == null) return null;
return resourceStore.findByName(getRoleResourceName(role), server.getId());
return resourceStore.findByName(server, getRoleResourceName(role));
}
@Override
@ -300,7 +300,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
ResourceServer resourceServer = resourceServer(role);
if (resourceServer == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getMapRolePermissionName(role), resourceServer.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(resourceServer, getMapRolePermissionName(role));
if (policy == null || policy.getAssociatedPolicies().isEmpty()) {
return false;
}
@ -390,7 +390,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
ResourceServer resourceServer = resourceServer(role);
if (resourceServer == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getMapCompositePermissionName(role), resourceServer.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(resourceServer, getMapCompositePermissionName(role));
if (policy == null || policy.getAssociatedPolicies().isEmpty()) {
return false;
}
@ -429,7 +429,7 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
ResourceServer resourceServer = resourceServer(role);
if (resourceServer == null) return false;
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(getMapClientScopePermissionName(role), resourceServer.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(resourceServer, getMapClientScopePermissionName(role));
if (policy == null || policy.getAssociatedPolicies().isEmpty()) {
return false;
}
@ -520,21 +520,21 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
@Override
public Policy rolePolicy(ResourceServer server, RoleModel role) {
String policyName = Helper.getRolePolicyName(role);
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(policyName, server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, policyName);
if (policy != null) return policy;
return Helper.createRolePolicy(authz, server, role, policyName);
}
private Scope mapRoleScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(MAP_ROLE_SCOPE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, MAP_ROLE_SCOPE);
}
private Scope mapClientScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(MAP_ROLE_CLIENT_SCOPE_SCOPE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, MAP_ROLE_CLIENT_SCOPE_SCOPE);
}
private Scope mapCompositeScope(ResourceServer server) {
return authz.getStoreFactory().getScopeStore().findByName(MAP_ROLE_COMPOSITE_SCOPE, server.getId());
return authz.getStoreFactory().getScopeStore().findByName(server, MAP_ROLE_COMPOSITE_SCOPE);
}
@ -546,21 +546,21 @@ class RolePermissions implements RolePermissionEvaluator, RolePermissionManageme
}
Scope mapRoleScope = mapRoleScope(server);
if (mapRoleScope == null) {
mapRoleScope = authz.getStoreFactory().getScopeStore().create(MAP_ROLE_SCOPE, server);
mapRoleScope = authz.getStoreFactory().getScopeStore().create(server, MAP_ROLE_SCOPE);
}
Scope mapClientScope = mapClientScope(server);
if (mapClientScope == null) {
mapClientScope = authz.getStoreFactory().getScopeStore().create(MAP_ROLE_CLIENT_SCOPE_SCOPE, server);
mapClientScope = authz.getStoreFactory().getScopeStore().create(server, MAP_ROLE_CLIENT_SCOPE_SCOPE);
}
Scope mapCompositeScope = mapCompositeScope(server);
if (mapCompositeScope == null) {
mapCompositeScope = authz.getStoreFactory().getScopeStore().create(MAP_ROLE_COMPOSITE_SCOPE, server);
mapCompositeScope = authz.getStoreFactory().getScopeStore().create(server, MAP_ROLE_COMPOSITE_SCOPE);
}
String roleResourceName = getRoleResourceName(role);
Resource resource = authz.getStoreFactory().getResourceStore().findByName(roleResourceName, server.getId());
Resource resource = authz.getStoreFactory().getResourceStore().findByName(server, roleResourceName);
if (resource == null) {
resource = authz.getStoreFactory().getResourceStore().create(roleResourceName, server, server.getId());
resource = authz.getStoreFactory().getResourceStore().create(server, roleResourceName, server.getClientId());
Set<Scope> scopeset = new HashSet<>();
scopeset.add(mapClientScope);
scopeset.add(mapCompositeScope);

View file

@ -39,10 +39,8 @@ import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.authorization.Permission;
import org.keycloak.services.ForbiddenException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@ -104,9 +102,9 @@ class UserPermissions implements UserPermissionEvaluator, UserPermissionManageme
Scope userImpersonatedScope = root.initializeRealmScope(USER_IMPERSONATED_SCOPE);
Scope manageGroupMembershipScope = root.initializeRealmScope(MANAGE_GROUP_MEMBERSHIP_SCOPE);
Resource usersResource = resourceStore.findByName(USERS_RESOURCE, server.getId());
Resource usersResource = resourceStore.findByName(server, USERS_RESOURCE);
if (usersResource == null) {
usersResource = resourceStore.create(USERS_RESOURCE, server, server.getId());
usersResource = resourceStore.create(server, USERS_RESOURCE, server.getClientId());
Set<Scope> scopeset = new HashSet<>();
scopeset.add(manageScope);
scopeset.add(viewScope);
@ -116,27 +114,27 @@ class UserPermissions implements UserPermissionEvaluator, UserPermissionManageme
scopeset.add(userImpersonatedScope);
usersResource.updateScopes(scopeset);
}
Policy managePermission = policyStore.findByName(MANAGE_PERMISSION_USERS, server.getId());
Policy managePermission = policyStore.findByName(server, MANAGE_PERMISSION_USERS);
if (managePermission == null) {
Helper.addEmptyScopePermission(authz, server, MANAGE_PERMISSION_USERS, usersResource, manageScope);
}
Policy viewPermission = policyStore.findByName(VIEW_PERMISSION_USERS, server.getId());
Policy viewPermission = policyStore.findByName(server, VIEW_PERMISSION_USERS);
if (viewPermission == null) {
Helper.addEmptyScopePermission(authz, server, VIEW_PERMISSION_USERS, usersResource, viewScope);
}
Policy mapRolesPermission = policyStore.findByName(MAP_ROLES_PERMISSION_USERS, server.getId());
Policy mapRolesPermission = policyStore.findByName(server, MAP_ROLES_PERMISSION_USERS);
if (mapRolesPermission == null) {
Helper.addEmptyScopePermission(authz, server, MAP_ROLES_PERMISSION_USERS, usersResource, mapRolesScope);
}
Policy membershipPermission = policyStore.findByName(MANAGE_GROUP_MEMBERSHIP_PERMISSION_USERS, server.getId());
Policy membershipPermission = policyStore.findByName(server, MANAGE_GROUP_MEMBERSHIP_PERMISSION_USERS);
if (membershipPermission == null) {
Helper.addEmptyScopePermission(authz, server, MANAGE_GROUP_MEMBERSHIP_PERMISSION_USERS, usersResource, manageGroupMembershipScope);
}
Policy impersonatePermission = policyStore.findByName(ADMIN_IMPERSONATING_PERMISSION, server.getId());
Policy impersonatePermission = policyStore.findByName(server, ADMIN_IMPERSONATING_PERMISSION);
if (impersonatePermission == null) {
Helper.addEmptyScopePermission(authz, server, ADMIN_IMPERSONATING_PERMISSION, usersResource, impersonateScope);
}
impersonatePermission = policyStore.findByName(USER_IMPERSONATED_PERMISSION, server.getId());
impersonatePermission = policyStore.findByName(server, USER_IMPERSONATED_PERMISSION);
if (impersonatePermission == null) {
Helper.addEmptyScopePermission(authz, server, USER_IMPERSONATED_PERMISSION, usersResource, userImpersonatedScope);
}
@ -160,7 +158,7 @@ class UserPermissions implements UserPermissionEvaluator, UserPermissionManageme
ResourceServer server = root.realmResourceServer();
if (server == null) return false;
Resource resource = resourceStore.findByName(USERS_RESOURCE, server.getId());
Resource resource = resourceStore.findByName(server, USERS_RESOURCE);
if (resource == null) return false;
Policy policy = managePermission();
@ -186,38 +184,38 @@ class UserPermissions implements UserPermissionEvaluator, UserPermissionManageme
ResourceServer server = root.realmResourceServer();
if (server == null) return null;
return resourceStore.findByName(USERS_RESOURCE, server.getId());
return resourceStore.findByName(server, USERS_RESOURCE);
}
@Override
public Policy managePermission() {
return policyStore.findByName(MANAGE_PERMISSION_USERS, root.realmResourceServer().getId());
return policyStore.findByName(root.realmResourceServer(), MANAGE_PERMISSION_USERS);
}
@Override
public Policy viewPermission() {
return policyStore.findByName(VIEW_PERMISSION_USERS, root.realmResourceServer().getId());
return policyStore.findByName(root.realmResourceServer(), VIEW_PERMISSION_USERS);
}
@Override
public Policy manageGroupMembershipPermission() {
return policyStore.findByName(MANAGE_GROUP_MEMBERSHIP_PERMISSION_USERS, root.realmResourceServer().getId());
return policyStore.findByName(root.realmResourceServer(), MANAGE_GROUP_MEMBERSHIP_PERMISSION_USERS);
}
@Override
public Policy mapRolesPermission() {
return policyStore.findByName(MAP_ROLES_PERMISSION_USERS, root.realmResourceServer().getId());
return policyStore.findByName(root.realmResourceServer(), MAP_ROLES_PERMISSION_USERS);
}
@Override
public Policy adminImpersonatingPermission() {
return policyStore.findByName(ADMIN_IMPERSONATING_PERMISSION, root.realmResourceServer().getId());
return policyStore.findByName(root.realmResourceServer(), ADMIN_IMPERSONATING_PERMISSION);
}
@Override
public Policy userImpersonatedPermission() {
return policyStore.findByName(USER_IMPERSONATED_PERMISSION, root.realmResourceServer().getId());
return policyStore.findByName(root.realmResourceServer(), USER_IMPERSONATED_PERMISSION);
}
/**
@ -373,13 +371,13 @@ class UserPermissions implements UserPermissionEvaluator, UserPermissionManageme
return true;
}
Resource resource = resourceStore.findByName(USERS_RESOURCE, server.getId());
Resource resource = resourceStore.findByName(server, USERS_RESOURCE);
if (resource == null) {
return true;
}
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(USER_IMPERSONATED_PERMISSION, server.getId());
Policy policy = authz.getStoreFactory().getPolicyStore().findByName(server, USER_IMPERSONATED_PERMISSION);
if (policy == null) {
return true;
@ -481,7 +479,7 @@ class UserPermissions implements UserPermissionEvaluator, UserPermissionManageme
return false;
}
Resource resource = resourceStore.findByName(USERS_RESOURCE, server.getId());
Resource resource = resourceStore.findByName(server, USERS_RESOURCE);
List<String> expectedScopes = Arrays.asList(scopes);
if (resource == null) {
@ -540,7 +538,7 @@ class UserPermissions implements UserPermissionEvaluator, UserPermissionManageme
policyStore.delete(policy.getId());
}
Resource usersResource = resourceStore.findByName(USERS_RESOURCE, server.getId());
Resource usersResource = resourceStore.findByName(server, USERS_RESOURCE);
if (usersResource != null) {
resourceStore.delete(usersResource.getId());
}

View file

@ -290,7 +290,7 @@ public class BrokerLinkAndTokenExchangeTest extends AbstractServletsAdapterTest
clientRep.addClient(client.getId());
clientRep.addClient(directExchanger.getId());
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientRep);
management.idps().exchangeToPermission(idp).addAssociatedPolicy(clientPolicy);
@ -300,7 +300,7 @@ public class BrokerLinkAndTokenExchangeTest extends AbstractServletsAdapterTest
clientImpersonateRep.setName("clientImpersonators");
clientImpersonateRep.addClient(directExchanger.getId());
server = management.realmResourceServer();
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientImpersonateRep);
management.users().setPermissionsEnabled(true);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

View file

@ -95,7 +95,7 @@ public class AuthzCleanupTest extends AbstractKeycloakTest {
representation.setLogic(Logic.POSITIVE);
representation.addRole(roleName, true);
return authz.getStoreFactory().getPolicyStore().create(representation, resourceServer);
return authz.getStoreFactory().getPolicyStore().create(resourceServer, representation);
}

View file

@ -40,7 +40,6 @@ import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.RepresentationToModel;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ClientScopeRepresentation;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
@ -274,7 +273,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
groupManagerRep.addUser("groupManager");
groupManagerRep.addUser("noMapperGroupManager");
ResourceServer server = permissions.realmResourceServer();
Policy groupManagerPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(groupManagerRep, server);
Policy groupManagerPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(server, groupManagerRep);
permissions.groups().manageMembersPermission(group).addAssociatedPolicy(groupManagerPolicy);
permissions.groups().manageMembershipPermission(group).addAssociatedPolicy(groupManagerPolicy);
permissions.groups().viewPermission(group).addAssociatedPolicy(groupManagerPolicy);
@ -288,7 +287,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
UserPolicyRepresentation userRep = new UserPolicyRepresentation();
userRep.setName("userClientMapper");
userRep.addUser("clientMapper");
Policy userPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(userRep, permissions.clients().resourceServer(client));
Policy userPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(permissions.clients().resourceServer(client), userRep);
clientMapperPolicy.addAssociatedPolicy(userPolicy);
UserModel clientManager = session.users().addUser(realm, "clientManager");
@ -300,7 +299,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
userRep = new UserPolicyRepresentation();
userRep.setName("clientManager");
userRep.addUser("clientManager");
userPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(userRep, permissions.clients().resourceServer(client));
userPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(permissions.clients().resourceServer(client), userRep);
clientManagerPolicy.addAssociatedPolicy(userPolicy);
@ -313,7 +312,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
userRep = new UserPolicyRepresentation();
userRep.setName("clientConfigure");
userRep.addUser("clientConfigurer");
userPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(userRep, permissions.clients().resourceServer(client));
userPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(permissions.clients().resourceServer(client), userRep);
clientConfigurePolicy.addAssociatedPolicy(userPolicy);
@ -326,7 +325,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
UserPolicyRepresentation groupViewMembersRep = new UserPolicyRepresentation();
groupViewMembersRep.setName("groupMemberViewers");
groupViewMembersRep.addUser("groupViewer");
Policy groupViewMembersPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(groupViewMembersRep, server);
Policy groupViewMembersPolicy = permissions.authz().getStoreFactory().getPolicyStore().create(server, groupViewMembersRep);
Policy groupViewMembersPermission = permissions.groups().viewMembersPermission(group);
groupViewMembersPermission.addAssociatedPolicy(groupViewMembersPolicy);
@ -825,7 +824,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
public static void invokeDelete(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName(TEST);
AdminPermissionManagement management = AdminPermissions.management(session, realm);
List<Resource> byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
List<Resource> byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer());
Assert.assertEquals(5, byResourceServer.size());
RoleModel removedRole = realm.getRole("removedRole");
realm.removeRole(removedRole);
@ -834,15 +833,15 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
client.removeRole(removedClientRole);
GroupModel group = KeycloakModelUtils.findGroupByPath(realm, "removedGroup");
realm.removeGroup(group);
byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer());
Assert.assertEquals(2, byResourceServer.size());
realm.removeClient(client.getId());
byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer());
Assert.assertEquals(1, byResourceServer.size());
management.users().setPermissionsEnabled(false);
Resource userResource = management.authz().getStoreFactory().getResourceStore().findByName("Users", management.realmResourceServer().getId());
Resource userResource = management.authz().getStoreFactory().getResourceStore().findByName(management.realmResourceServer(), "Users");
Assert.assertNull(userResource);
byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer());
Assert.assertEquals(0, byResourceServer.size());
}
@ -1002,7 +1001,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
Policy userPolicy = provider.getStoreFactory().getPolicyStore().create(userPolicyRepresentation, management.realmResourceServer());
Policy userPolicy = provider.getStoreFactory().getPolicyStore().create(management.realmResourceServer(), userPolicyRepresentation);
policy.addAssociatedPolicy(RepresentationToModel.toModel(userPolicyRepresentation, provider, userPolicy));
@ -1096,7 +1095,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
Policy policy = clientPermission.viewPermission(clientModel);
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
Policy userPolicy = provider.getStoreFactory().getPolicyStore()
.create(userPolicyRepresentation, management.realmResourceServer());
.create(management.realmResourceServer(), userPolicyRepresentation);
policy.addAssociatedPolicy(RepresentationToModel.toModel(userPolicyRepresentation, provider, userPolicy));
});
@ -1127,8 +1126,9 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
ResourceServer resourceServer = provider.getStoreFactory().getResourceServerStore().findByClient(realmAdminClient);
policy.addAssociatedPolicy(provider.getStoreFactory().getPolicyStore().findByName("Only regular-admin-user", realmAdminClient.getId()));
policy.addAssociatedPolicy(provider.getStoreFactory().getPolicyStore().findByName(resourceServer, "Only regular-admin-user"));
});
try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth",
@ -1194,9 +1194,10 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
ResourceServer resourceServer = provider.getStoreFactory().getResourceServerStore().findByClient(realmAdminClient);
policy.addAssociatedPolicy(provider.getStoreFactory().getPolicyStore()
.findByName("Only regular-admin-user", realmAdminClient.getId()));
.findByName(resourceServer, "Only regular-admin-user"));
}
});
@ -1275,11 +1276,11 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
if (i == 15) {
provider.getStoreFactory().getPolicyStore()
.create(userPolicyRepresentation, management.realmResourceServer());
.create(management.realmResourceServer(), userPolicyRepresentation);
}
policy.addAssociatedPolicy(provider.getStoreFactory().getPolicyStore()
.findByName("Only regular-admin-user", realmAdminClient.getId()));
.findByName(management.realmResourceServer(), "Only regular-admin-user"));
}
});
@ -1362,7 +1363,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
clientRep.setName("to");
clientRep.addClient(tokenexclient.getId());
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientRep);
management.clients().exchangeToPermission(adminCli).addAssociatedPolicy(clientPolicy);
}
}

View file

@ -78,8 +78,8 @@ public class PolicyEvaluationCompositeRoleTest extends AbstractAuthzTest {
ResourceServer resourceServer = authz.getStoreFactory().getResourceServerStore().create(client);
Policy policy = createRolePolicy(authz, resourceServer, role1);
Scope scope = authz.getStoreFactory().getScopeStore().create("myscope", resourceServer);
Resource resource = authz.getStoreFactory().getResourceStore().create("myresource", resourceServer, resourceServer.getId());
Scope scope = authz.getStoreFactory().getScopeStore().create(resourceServer, "myscope");
Resource resource = authz.getStoreFactory().getResourceStore().create(resourceServer, "myresource", resourceServer.getClientId());
addScopePermission(authz, resourceServer, "mypermission", resource, scope, policy);
RoleModel composite = realm.addRole("composite");
@ -100,7 +100,7 @@ public class PolicyEvaluationCompositeRoleTest extends AbstractAuthzTest {
representation.setDecisionStrategy(DecisionStrategy.UNANIMOUS);
representation.setLogic(Logic.POSITIVE);
return authz.getStoreFactory().getPolicyStore().create(representation, resourceServer);
return authz.getStoreFactory().getPolicyStore().create(resourceServer, representation);
}
@ -116,7 +116,7 @@ public class PolicyEvaluationCompositeRoleTest extends AbstractAuthzTest {
config.put("roles", roleValues);
representation.setConfig(config);
return authz.getStoreFactory().getPolicyStore().create(representation, resourceServer);
return authz.getStoreFactory().getPolicyStore().create(resourceServer, representation);
}

View file

@ -145,7 +145,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setNotOnOrAfter(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(notOnOrAfterDate));
// evaluation should succeed with the default context as it uses the current time as the date to be compared.
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
provider.evaluate(evaluation);
@ -181,7 +181,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -340,7 +340,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -387,7 +387,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -434,7 +434,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -482,7 +482,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -514,7 +514,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -546,7 +546,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -584,7 +584,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -617,9 +617,9 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType());
Resource resource = storeFactory.getResourceStore().create("testCheckResourceAttributesResource", resourceServer, resourceServer.getId());
Resource resource = storeFactory.getResourceStore().create(resourceServer, "testCheckResourceAttributesResource", resourceServer.getClientId());
resource.setAttribute("a1", Arrays.asList("1", "2"));
resource.setAttribute("a2", Arrays.asList("3"));
@ -651,10 +651,10 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
Resource resource = storeFactory.getResourceStore().create("Resource A", resourceServer, resourceServer.getId());
Scope scope = storeFactory.getScopeStore().create("Scope A", resourceServer);
Resource resource = storeFactory.getResourceStore().create(resourceServer, "Resource A", resourceServer.getClientId());
Scope scope = storeFactory.getScopeStore().create(resourceServer, "Scope A");
resource.updateScopes(new HashSet<>(Arrays.asList(scope)));
@ -664,7 +664,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
permission.addPolicy(policy.getId());
permission.addResource(resource.getId());
storeFactory.getPolicyStore().create(permission, resourceServer);
storeFactory.getPolicyStore().create(resourceServer, permission);
session.getTransactionManager().commit();
@ -689,8 +689,8 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
Scope readScope = storeFactory.getScopeStore().create("read", resourceServer);
Scope writeScope = storeFactory.getScopeStore().create("write", resourceServer);
Scope readScope = storeFactory.getScopeStore().create(resourceServer, "read");
Scope writeScope = storeFactory.getScopeStore().create(resourceServer, "write");
JSPolicyRepresentation policy = new JSPolicyRepresentation();
@ -698,7 +698,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
policy.setCode("$evaluation.grant()");
policy.setLogic(Logic.NEGATIVE);
storeFactory.getPolicyStore().create(policy, resourceServer);
storeFactory.getPolicyStore().create(resourceServer, policy);
ScopePermissionRepresentation readPermission = new ScopePermissionRepresentation();
@ -706,7 +706,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
readPermission.addScope(readScope.getId());
readPermission.addPolicy(policy.getName());
storeFactory.getPolicyStore().create(readPermission, resourceServer);
storeFactory.getPolicyStore().create(resourceServer, readPermission);
ScopePermissionRepresentation writePermission = new ScopePermissionRepresentation();
@ -714,9 +714,9 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
writePermission.addScope(writeScope.getId());
writePermission.addPolicy(policy.getName());
storeFactory.getPolicyStore().create(writePermission, resourceServer);
storeFactory.getPolicyStore().create(resourceServer, writePermission);
Resource resource = storeFactory.getResourceStore().create(KeycloakModelUtils.generateId(), resourceServer, resourceServer.getId());
Resource resource = storeFactory.getResourceStore().create(resourceServer, KeycloakModelUtils.generateId(), resourceServer.getClientId());
PermissionEvaluator evaluator = authorization.evaluators().from(Arrays.asList(new ResourcePermission(resource, Arrays.asList(readScope, writeScope), resourceServer)), createEvaluationContext(session, Collections.emptyMap()));
Collection<Permission> permissions = evaluator.evaluate(resourceServer, null);

View file

@ -16,6 +16,7 @@ import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;
import java.util.List;
import org.keycloak.authorization.model.ResourceServer;
@AuthServerContainerExclude(AuthServer.REMOTE)
public class UmaRepresentationTest extends AbstractResourceServerTest {
@ -139,9 +140,10 @@ public class UmaRepresentationTest extends AbstractResourceServerTest {
AuthorizationBean authorizationBean = new AuthorizationBean(session, null, session.getContext().getUri());
ClientModel client = session.getContext().getRealm().getClientByClientId("resource-server-test");
UserModel user = session.userStorageManager().getUserByUsername(session.getContext().getRealm(), "marta");
ResourceServer resourceServer = authorization.getStoreFactory().getResourceServerStore().findByClient(client);
ResourceBean resourceBean = authorizationBean.new ResourceBean(
authorization.getStoreFactory().getResourceStore().findByName(
"Resource A", user.getId(), client.getId()
resourceServer, "Resource A", user.getId()
)
);
@ -164,9 +166,10 @@ public class UmaRepresentationTest extends AbstractResourceServerTest {
AuthorizationBean authorizationBean = new AuthorizationBean(session, null, session.getContext().getUri());
ClientModel client = session.getContext().getRealm().getClientByClientId("resource-server-test");
ResourceServer resourceServer = authorization.getStoreFactory().getResourceServerStore().findByClient(client);
ResourceBean resourceBean = authorizationBean.new ResourceBean(
authorization.getStoreFactory().getResourceStore().findByName(
"Resource A", client.getId(), client.getId()
resourceServer, "Resource A", client.getId()
)
);

View file

@ -41,6 +41,7 @@ import org.keycloak.authorization.client.resource.ProtectionResource;
import org.keycloak.authorization.client.util.HttpResponseException;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.common.Profile;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
@ -916,13 +917,14 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
ClientModel client = realm.getClientByClientId("resource-server-test");
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
UserModel user = session.users().getUserByUsername(realm, "marta");
ResourceServer resourceServer = provider.getStoreFactory().getResourceServerStore().findByClient(client);
Map<Policy.FilterOption, String[]> filters = new HashMap<>();
filters.put(Policy.FilterOption.TYPE, new String[] {"uma"});
filters.put(OWNER, new String[] {user.getId()});
List<Policy> policies = provider.getStoreFactory().getPolicyStore()
.findByResourceServer(filters, client.getId(), -1, -1);
.findByResourceServer(resourceServer, filters, null, null);
assertEquals(1, policies.size());
Policy policy = policies.get(0);
@ -937,7 +939,7 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
filters.put(OWNER, new String[] {user.getId()});
policies = provider.getStoreFactory().getPolicyStore()
.findByResourceServer(filters, client.getId(), -1, -1);
.findByResourceServer(resourceServer, filters, null, null);
assertTrue(policies.isEmpty());
}
@ -969,13 +971,14 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
ClientModel client = realm.getClientByClientId("resource-server-test");
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
UserModel user = session.users().getUserByUsername(realm, "marta");
ResourceServer resourceServer = provider.getStoreFactory().getResourceServerStore().findByClient(client);
Map<Policy.FilterOption, String[]> filters = new HashMap<>();
filters.put(Policy.FilterOption.TYPE, new String[] {"uma"});
filters.put(OWNER, new String[] {user.getId()});
List<Policy> policies = provider.getStoreFactory().getPolicyStore()
.findByResourceServer(filters, client.getId(), -1, -1);
.findByResourceServer(resourceServer, filters, null, null);
assertEquals(1, policies.size());
Policy policy = policies.get(0);
@ -991,7 +994,7 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
filters.put(OWNER, new String[] {user.getId()});
policies = provider.getStoreFactory().getPolicyStore()
.findByResourceServer(filters, client.getId(), -1, -1);
.findByResourceServer(resourceServer, filters, null, null);
assertTrue(policies.isEmpty());
}
@ -1023,13 +1026,14 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
ClientModel client = realm.getClientByClientId("resource-server-test");
AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
UserModel user = session.users().getUserByUsername(realm, "marta");
ResourceServer resourceServer = provider.getStoreFactory().getResourceServerStore().findByClient(client);
Map<Policy.FilterOption, String[]> filters = new HashMap<>();
filters.put(Policy.FilterOption.TYPE, new String[] {"uma"});
filters.put(OWNER, new String[] {user.getId()});
List<Policy> policies = provider.getStoreFactory().getPolicyStore()
.findByResourceServer(filters, client.getId(), -1, -1);
.findByResourceServer(resourceServer, filters, null, null);
assertEquals(1, policies.size());
Policy policy = policies.get(0);
@ -1045,7 +1049,7 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
filters.put(OWNER, new String[] {user.getId()});
policies = provider.getStoreFactory().getPolicyStore()
.findByResourceServer(filters, client.getId(), -1, -1);
.findByResourceServer(resourceServer, filters, null, null);
assertTrue(policies.isEmpty());
}

View file

@ -232,7 +232,7 @@ public class SocialLoginTest extends AbstractKeycloakTest {
AdminPermissionManagement management = AdminPermissions.management(session, realm);
management.users().setPermissionsEnabled(true);
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientPolicyRep, server);
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientPolicyRep);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientPolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
realm.getIdentityProvidersStream().forEach(idp -> {

View file

@ -203,7 +203,7 @@ public class ClientTokenExchangeSAML2Test extends AbstractKeycloakTest {
assertNotNull(samlUnsignedAndUnencryptedTarget);
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientRep);
management.clients().exchangeToPermission(samlSignedTarget).addAssociatedPolicy(clientPolicy);
management.clients().exchangeToPermission(samlEncryptedTarget).addAssociatedPolicy(clientPolicy);
management.clients().exchangeToPermission(samlSignedAndEncryptedTarget).addAssociatedPolicy(clientPolicy);
@ -217,7 +217,7 @@ public class ClientTokenExchangeSAML2Test extends AbstractKeycloakTest {
clientImpersonateRep.addClient(directPublic.getId());
clientImpersonateRep.addClient(directNoSecret.getId());
server = management.realmResourceServer();
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientImpersonateRep);
management.users().setPermissionsEnabled(true);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
@ -697,7 +697,7 @@ public class ClientTokenExchangeSAML2Test extends AbstractKeycloakTest {
clientImpersonateRep.addClient(directExchanger.getId());
ResourceServer server = management.realmResourceServer();
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientImpersonateRep);
management.users().setPermissionsEnabled(true);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

View file

@ -203,7 +203,7 @@ public class ClientTokenExchangeTest extends AbstractKeycloakTest {
clientRep.addClient(noRefreshToken.getId());
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientRep);
management.clients().exchangeToPermission(target).addAssociatedPolicy(clientPolicy);
// permission for user impersonation for a client
@ -214,7 +214,7 @@ public class ClientTokenExchangeTest extends AbstractKeycloakTest {
clientImpersonateRep.addClient(directPublic.getId());
clientImpersonateRep.addClient(directNoSecret.getId());
server = management.realmResourceServer();
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientImpersonateRep);
management.users().setPermissionsEnabled(true);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
@ -559,7 +559,7 @@ public class ClientTokenExchangeTest extends AbstractKeycloakTest {
clientImpersonateRep.addClient(directExchanger.getId());
ResourceServer server = management.realmResourceServer();
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(server, clientImpersonateRep);
management.users().setPermissionsEnabled(true);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);