Search in sources :

Example 16 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class StoreFactoryCacheSession method getResourceTypes.

private Set<String> getResourceTypes(Set<String> resources, String serverId) {
    if (resources == null) {
        return Collections.emptySet();
    }
    return resources.stream().map(resourceId -> {
        Resource resource = getResourceStore().findById(resourceId, serverId);
        String type = resource.getType();
        if (type != null) {
            return type;
        }
        return null;
    }).filter(Objects::nonNull).collect(Collectors.toSet());
}
Also used : CachedResource(org.keycloak.models.cache.infinispan.authorization.entities.CachedResource) Resource(org.keycloak.authorization.model.Resource)

Example 17 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class MapUserProvider method searchForUserStream.

@Override
public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, String> attributes, Integer firstResult, Integer maxResults) {
    LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, attributes, firstResult, maxResults, getShortStackTrace());
    final DefaultModelCriteria<UserModel> mcb = criteria();
    DefaultModelCriteria<UserModel> criteria = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId());
    if (!session.getAttributeOrDefault(UserModel.INCLUDE_SERVICE_ACCOUNT, true)) {
        criteria = criteria.compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.NOT_EXISTS);
    }
    final boolean exactSearch = Boolean.parseBoolean(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString()));
    for (Map.Entry<String, String> entry : attributes.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (value == null) {
            continue;
        }
        value = value.trim();
        final String searchedString = exactSearch ? value : ("%" + value + "%");
        switch(key) {
            case UserModel.SEARCH:
                DefaultModelCriteria<UserModel> searchCriteria = null;
                for (String stringToSearch : value.split("\\s+")) {
                    if (searchCriteria == null) {
                        searchCriteria = addSearchToModelCriteria(stringToSearch, mcb);
                    } else {
                        searchCriteria = mcb.and(searchCriteria, addSearchToModelCriteria(stringToSearch, mcb));
                    }
                }
                criteria = mcb.and(criteria, searchCriteria);
                break;
            case USERNAME:
                criteria = criteria.compare(SearchableFields.USERNAME, Operator.ILIKE, searchedString);
                break;
            case FIRST_NAME:
                criteria = criteria.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, searchedString);
                break;
            case LAST_NAME:
                criteria = criteria.compare(SearchableFields.LAST_NAME, Operator.ILIKE, searchedString);
                break;
            case EMAIL:
                criteria = criteria.compare(SearchableFields.EMAIL, Operator.ILIKE, searchedString);
                break;
            case EMAIL_VERIFIED:
                {
                    boolean booleanValue = Boolean.parseBoolean(value);
                    criteria = criteria.compare(SearchableFields.EMAIL_VERIFIED, Operator.EQ, booleanValue);
                    break;
                }
            case UserModel.ENABLED:
                {
                    boolean booleanValue = Boolean.parseBoolean(value);
                    criteria = criteria.compare(SearchableFields.ENABLED, Operator.EQ, booleanValue);
                    break;
                }
            case UserModel.IDP_ALIAS:
                {
                    if (!attributes.containsKey(UserModel.IDP_USER_ID)) {
                        criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, value);
                    }
                    break;
                }
            case UserModel.IDP_USER_ID:
                {
                    criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, attributes.get(UserModel.IDP_ALIAS), value);
                    break;
                }
            case UserModel.EXACT:
                break;
            default:
                criteria = criteria.compare(SearchableFields.ATTRIBUTE, Operator.EQ, key, value);
                break;
        }
    }
    // Only return those results that the current user is authorized to view,
    // i.e. there is an intersection of groups with view permission of the current
    // user (passed in via UserModel.GROUPS attribute), the groups for the returned
    // users, and the respective group resource available from the authorization provider
    @SuppressWarnings("unchecked") Set<String> userGroups = (Set<String>) session.getAttribute(UserModel.GROUPS);
    if (userGroups != null) {
        if (userGroups.isEmpty()) {
            return Stream.empty();
        }
        final ResourceStore resourceStore = session.getProvider(AuthorizationProvider.class).getStoreFactory().getResourceStore();
        HashSet<String> authorizedGroups = new HashSet<>(userGroups);
        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();
        });
        criteria = criteria.compare(SearchableFields.ASSIGNED_GROUP, Operator.IN, authorizedGroups);
    }
    return tx.read(withCriteria(criteria).pagination(firstResult, maxResults, SearchableFields.USERNAME)).map(entityToAdapterFunc(realm)).filter(Objects::nonNull);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) UserModel(org.keycloak.models.UserModel) Objects(java.util.Objects) Map(java.util.Map) EnumMap(java.util.EnumMap) HashMap(java.util.HashMap) EnumMap(java.util.EnumMap) HashSet(java.util.HashSet)

Example 18 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class PermissionTicketAwareDecisionResultCollector method onComplete.

@Override
public void onComplete() {
    super.onComplete();
    if (request.isSubmitRequest()) {
        StoreFactory storeFactory = authorization.getStoreFactory();
        ResourceStore resourceStore = storeFactory.getResourceStore();
        List<Permission> permissions = ticket.getPermissions();
        if (permissions != null) {
            for (Permission permission : permissions) {
                Resource resource = resourceStore.findById(permission.getResourceId(), resourceServer.getId());
                if (resource == null) {
                    resource = resourceStore.findByName(permission.getResourceId(), identity.getId(), resourceServer.getId());
                }
                if (resource == null || !resource.isOwnerManagedAccess() || resource.getOwner().equals(identity.getId()) || resource.getOwner().equals(resourceServer.getId())) {
                    continue;
                }
                Set<String> scopes = permission.getScopes();
                if (scopes.isEmpty()) {
                    scopes = resource.getScopes().stream().map(Scope::getName).collect(Collectors.toSet());
                }
                if (scopes.isEmpty()) {
                    Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
                    filters.put(PermissionTicket.FilterOption.RESOURCE_ID, resource.getId());
                    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);
                    if (tickets.isEmpty()) {
                        authorization.getStoreFactory().getPermissionTicketStore().create(resource.getId(), null, identity.getId(), resourceServer);
                    }
                } else {
                    ScopeStore scopeStore = authorization.getStoreFactory().getScopeStore();
                    for (String scopeId : scopes) {
                        Scope scope = scopeStore.findByName(scopeId, resourceServer.getId());
                        if (scope == null) {
                            scope = scopeStore.findById(scopeId, resourceServer.getId());
                        }
                        Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
                        filters.put(PermissionTicket.FilterOption.RESOURCE_ID, resource.getId());
                        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);
                        if (tickets.isEmpty()) {
                            authorization.getStoreFactory().getPermissionTicketStore().create(resource.getId(), scope.getId(), identity.getId(), resourceServer);
                        }
                    }
                }
            }
        }
    }
}
Also used : PermissionTicket(org.keycloak.authorization.model.PermissionTicket) Resource(org.keycloak.authorization.model.Resource) ScopeStore(org.keycloak.authorization.store.ScopeStore) ResourceStore(org.keycloak.authorization.store.ResourceStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) Scope(org.keycloak.authorization.model.Scope) Permission(org.keycloak.representations.idm.authorization.Permission) EnumMap(java.util.EnumMap)

Example 19 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class AuthorizationProvider method createResourceStoreWrapper.

private ResourceStore createResourceStoreWrapper(StoreFactory storeFactory) {
    return new ResourceStore() {

        ResourceStore delegate = storeFactory.getResourceStore();

        @Override
        public Resource create(String name, ResourceServer resourceServer, String owner) {
            return delegate.create(name, resourceServer, owner);
        }

        @Override
        public Resource create(String id, String name, ResourceServer resourceServer, String owner) {
            return delegate.create(id, name, resourceServer, owner);
        }

        @Override
        public void delete(String id) {
            Resource resource = findById(id, null);
            StoreFactory storeFactory = AuthorizationProvider.this.getStoreFactory();
            PermissionTicketStore ticketStore = storeFactory.getPermissionTicketStore();
            List<PermissionTicket> permissions = ticketStore.findByResource(id, resource.getResourceServer());
            for (PermissionTicket permission : permissions) {
                ticketStore.delete(permission.getId());
            }
            PolicyStore policyStore = storeFactory.getPolicyStore();
            List<Policy> policies = policyStore.findByResource(id, resource.getResourceServer());
            for (Policy policyModel : policies) {
                if (policyModel.getResources().size() == 1) {
                    policyStore.delete(policyModel.getId());
                } else {
                    policyModel.removeResource(resource);
                }
            }
            delegate.delete(id);
        }

        @Override
        public Resource findById(String id, String resourceServerId) {
            return delegate.findById(id, resourceServerId);
        }

        @Override
        public List<Resource> findByOwner(String ownerId, String resourceServerId) {
            return delegate.findByOwner(ownerId, resourceServerId);
        }

        @Override
        public void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer) {
            delegate.findByOwner(ownerId, resourceServerId, consumer);
        }

        @Override
        public List<Resource> findByOwner(String ownerId, String resourceServerId, int first, int max) {
            return delegate.findByOwner(ownerId, resourceServerId, first, max);
        }

        @Override
        public List<Resource> findByUri(String uri, String resourceServerId) {
            return delegate.findByUri(uri, resourceServerId);
        }

        @Override
        public List<Resource> findByResourceServer(String resourceServerId) {
            return delegate.findByResourceServer(resourceServerId);
        }

        @Override
        public List<Resource> findByResourceServer(Map<Resource.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
            return delegate.findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
        }

        @Override
        public List<Resource> findByScope(List<String> id, String resourceServerId) {
            return delegate.findByScope(id, resourceServerId);
        }

        @Override
        public void findByScope(List<String> scopes, String resourceServerId, Consumer<Resource> consumer) {
            delegate.findByScope(scopes, resourceServerId, consumer);
        }

        @Override
        public Resource findByName(String name, String resourceServerId) {
            return delegate.findByName(name, resourceServerId);
        }

        @Override
        public Resource findByName(String name, String ownerId, String resourceServerId) {
            return delegate.findByName(name, ownerId, resourceServerId);
        }

        @Override
        public List<Resource> findByType(String type, String resourceServerId) {
            return delegate.findByType(type, resourceServerId);
        }

        @Override
        public void findByType(String type, String resourceServerId, Consumer<Resource> consumer) {
            delegate.findByType(type, resourceServerId, consumer);
        }

        @Override
        public void findByType(String type, String owner, String resourceServerId, Consumer<Resource> consumer) {
            delegate.findByType(type, owner, resourceServerId, consumer);
        }

        @Override
        public List<Resource> findByType(String type, String owner, String resourceServerId) {
            return delegate.findByType(type, resourceServerId);
        }

        @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);
        }
    };
}
Also used : Policy(org.keycloak.authorization.model.Policy) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) Consumer(java.util.function.Consumer) PermissionTicketStore(org.keycloak.authorization.store.PermissionTicketStore) PolicyStore(org.keycloak.authorization.store.PolicyStore) List(java.util.List) ResourceServer(org.keycloak.authorization.model.ResourceServer) Map(java.util.Map)

Example 20 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class ExportUtils method createPolicyRepresentation.

private static PolicyRepresentation createPolicyRepresentation(AuthorizationProvider authorizationProvider, Policy policy) {
    try {
        PolicyRepresentation rep = toRepresentation(policy, authorizationProvider, true, true);
        Map<String, String> config = new HashMap<>(rep.getConfig());
        rep.setConfig(config);
        Set<Scope> scopes = policy.getScopes();
        if (!scopes.isEmpty()) {
            List<String> scopeNames = scopes.stream().map(Scope::getName).collect(Collectors.toList());
            config.put("scopes", JsonSerialization.writeValueAsString(scopeNames));
        }
        Set<Resource> policyResources = policy.getResources();
        if (!policyResources.isEmpty()) {
            List<String> resourceNames = policyResources.stream().map(Resource::getName).collect(Collectors.toList());
            config.put("resources", JsonSerialization.writeValueAsString(resourceNames));
        }
        Set<Policy> associatedPolicies = policy.getAssociatedPolicies();
        if (!associatedPolicies.isEmpty()) {
            config.put("applyPolicies", JsonSerialization.writeValueAsString(associatedPolicies.stream().map(associated -> associated.getName()).collect(Collectors.toList())));
        }
        return rep;
    } catch (Exception e) {
        throw new RuntimeException("Error while exporting policy [" + policy.getName() + "].", e);
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Version(org.keycloak.common.Version) RoleContainerModel(org.keycloak.models.RoleContainerModel) Map(java.util.Map) ModelToRepresentation.toRepresentation(org.keycloak.models.utils.ModelToRepresentation.toRepresentation) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) UserConsentRepresentation(org.keycloak.representations.idm.UserConsentRepresentation) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Collection(java.util.Collection) AuthorizationProviderFactory(org.keycloak.authorization.AuthorizationProviderFactory) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) PolicyStore(org.keycloak.authorization.store.PolicyStore) Collectors(java.util.stream.Collectors) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) List(java.util.List) Stream(java.util.stream.Stream) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) Profile(org.keycloak.common.Profile) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ScopeMappingRepresentation(org.keycloak.representations.idm.ScopeMappingRepresentation) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) LinkedList(java.util.LinkedList) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ResourceServer(org.keycloak.authorization.model.ResourceServer) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) OutputStream(java.io.OutputStream) RolesRepresentation(org.keycloak.representations.idm.RolesRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) CredentialModel(org.keycloak.credential.CredentialModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) JsonSerialization(org.keycloak.util.JsonSerialization) Policy(org.keycloak.authorization.model.Policy) JsonFactory(com.fasterxml.jackson.core.JsonFactory) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) Resource(org.keycloak.authorization.model.Resource) HashMap(java.util.HashMap) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) Resource(org.keycloak.authorization.model.Resource) IOException(java.io.IOException) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) Scope(org.keycloak.authorization.model.Scope)

Aggregations

Resource (org.keycloak.authorization.model.Resource)87 ResourceServer (org.keycloak.authorization.model.ResourceServer)51 Policy (org.keycloak.authorization.model.Policy)45 Scope (org.keycloak.authorization.model.Scope)44 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)27 ResourceStore (org.keycloak.authorization.store.ResourceStore)27 StoreFactory (org.keycloak.authorization.store.StoreFactory)26 ArrayList (java.util.ArrayList)22 ClientModel (org.keycloak.models.ClientModel)22 List (java.util.List)20 HashSet (java.util.HashSet)19 Map (java.util.Map)19 UserModel (org.keycloak.models.UserModel)18 RealmModel (org.keycloak.models.RealmModel)16 HashMap (java.util.HashMap)15 Set (java.util.Set)15 EnumMap (java.util.EnumMap)14 Collectors (java.util.stream.Collectors)14 Path (javax.ws.rs.Path)13 PolicyStore (org.keycloak.authorization.store.PolicyStore)13