Search in sources :

Example 41 with Resource

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

the class PolicyEvaluationCompositeRoleTest method setup.

public static void setup(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    session.getContext().setRealm(realm);
    ClientModel client = session.clients().addClient(realm, "myclient");
    RoleModel role1 = client.addRole("client-role1");
    AuthorizationProviderFactory factory = (AuthorizationProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(AuthorizationProvider.class);
    AuthorizationProvider authz = factory.create(session, realm);
    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());
    addScopePermission(authz, resourceServer, "mypermission", resource, scope, policy);
    RoleModel composite = realm.addRole("composite");
    composite.addCompositeRole(role1);
    UserModel user = session.users().addUser(realm, "user");
    user.grantRole(composite);
}
Also used : RealmModel(org.keycloak.models.RealmModel) Policy(org.keycloak.authorization.model.Policy) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) RealmResource(org.keycloak.admin.client.resource.RealmResource) Resource(org.keycloak.authorization.model.Resource) AuthorizationProviderFactory(org.keycloak.authorization.AuthorizationProviderFactory) RoleModel(org.keycloak.models.RoleModel) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 42 with Resource

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

the class ResourceAdapter method updateScopes.

@Override
public void updateScopes(Set<Scope> scopes) {
    Resource updated = getDelegateForUpdate();
    for (Scope scope : updated.getScopes()) {
        if (!scopes.contains(scope)) {
            PermissionTicketStore permissionStore = cacheSession.getPermissionTicketStore();
            List<PermissionTicket> permissions = permissionStore.findByScope(scope.getId(), getResourceServer());
            for (PermissionTicket permission : permissions) {
                permissionStore.delete(permission.getId());
            }
        }
    }
    PolicyStore policyStore = cacheSession.getPolicyStore();
    for (Scope scope : updated.getScopes()) {
        if (!scopes.contains(scope)) {
            policyStore.findByResource(getId(), getResourceServer(), policy -> policy.removeScope(scope));
        }
    }
    cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), cached.getUris(modelSupplier), scopes.stream().map(scope1 -> scope1.getId()).collect(Collectors.toSet()), cached.getResourceServerId(), cached.getOwner());
    updated.updateScopes(scopes);
}
Also used : PermissionTicket(org.keycloak.authorization.model.PermissionTicket) Scope(org.keycloak.authorization.model.Scope) PermissionTicketStore(org.keycloak.authorization.store.PermissionTicketStore) CachedResource(org.keycloak.models.cache.infinispan.authorization.entities.CachedResource) Resource(org.keycloak.authorization.model.Resource) PolicyStore(org.keycloak.authorization.store.PolicyStore)

Example 43 with Resource

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

the class DecisionPermissionCollector method onComplete.

@Override
public void onComplete(Result result) {
    ResourcePermission permission = result.getPermission();
    Resource resource = permission.getResource();
    Collection<Scope> requestedScopes = permission.getScopes();
    if (Effect.PERMIT.equals(result.getEffect())) {
        if (permission.getScopes().isEmpty() && !resource.getScopes().isEmpty()) {
            return;
        }
        grantPermission(authorizationProvider, permissions, permission, requestedScopes, resourceServer, request, result);
    } else {
        Set<Scope> grantedScopes = new HashSet<>();
        Set<Scope> deniedScopes = new HashSet<>();
        List<Result.PolicyResult> userManagedPermissions = new ArrayList<>();
        boolean resourceGranted = false;
        boolean anyDeny = false;
        for (Result.PolicyResult policyResult : result.getResults()) {
            Policy policy = policyResult.getPolicy();
            Set<Scope> policyScopes = policy.getScopes();
            Set<Resource> policyResources = policy.getResources();
            boolean containsResource = policyResources.contains(resource);
            if (isGranted(policyResult)) {
                if (isScopePermission(policy)) {
                    for (Scope scope : requestedScopes) {
                        if (policyScopes.contains(scope)) {
                            grantedScopes.add(scope);
                            // associated with the resource. For instance, resources inheriting scopes from parent resources.
                            if (resource != null && !resource.getScopes().contains(scope)) {
                                deniedScopes.remove(scope);
                            }
                        }
                    }
                } else if (isResourcePermission(policy)) {
                    grantedScopes.addAll(requestedScopes);
                } else if (resource != null && resource.isOwnerManagedAccess() && "uma".equals(policy.getType())) {
                    userManagedPermissions.add(policyResult);
                }
                if (!resourceGranted) {
                    resourceGranted = isGrantingAccessToResource(resource, policy) && containsResource;
                }
            } else {
                if (isResourcePermission(policy)) {
                    // resource was not granted by any other permission
                    if (containsResource || !resourceGranted) {
                        deniedScopes.addAll(requestedScopes);
                    }
                } else {
                    // resource or if the permission applies to any resource associated with the scopes
                    if (containsResource || policyResources.isEmpty()) {
                        deniedScopes.addAll(policyScopes);
                    }
                }
                if (!anyDeny) {
                    anyDeny = true;
                }
            }
        }
        if (DecisionStrategy.AFFIRMATIVE.equals(resourceServer.getDecisionStrategy())) {
            // remove any scope that was granted from the list of denied scopes if the decision strategy is affirmative
            deniedScopes.removeAll(grantedScopes);
        }
        grantedScopes.removeAll(deniedScopes);
        if (userManagedPermissions.isEmpty()) {
            if (!resourceGranted && (grantedScopes.isEmpty() && !requestedScopes.isEmpty())) {
                return;
            }
        } else {
            for (Result.PolicyResult userManagedPermission : userManagedPermissions) {
                Set<Scope> scopes = new HashSet<>(userManagedPermission.getPolicy().getScopes());
                if (!requestedScopes.isEmpty()) {
                    scopes.retainAll(requestedScopes);
                }
                grantedScopes.addAll(scopes);
            }
            if (grantedScopes.isEmpty() && !resource.getScopes().isEmpty()) {
                return;
            }
            anyDeny = false;
        }
        if (anyDeny && grantedScopes.isEmpty()) {
            return;
        }
        grantPermission(authorizationProvider, permissions, permission, grantedScopes, resourceServer, request, result);
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) Scope(org.keycloak.authorization.model.Scope) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 44 with Resource

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

the class DecisionPermissionCollector method grantPermission.

protected void grantPermission(AuthorizationProvider authorizationProvider, Set<Permission> permissions, ResourcePermission permission, Collection<Scope> grantedScopes, ResourceServer resourceServer, AuthorizationRequest request, Result result) {
    Set<String> scopeNames = grantedScopes.stream().map(Scope::getName).collect(Collectors.toSet());
    Resource resource = permission.getResource();
    if (resource != null) {
        permissions.add(createPermission(resource, scopeNames, permission.getClaims(), request));
    } 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)));
        permissions.add(createPermission(null, scopeNames, permission.getClaims(), request));
    }
}
Also used : ResourceServer(org.keycloak.authorization.model.ResourceServer) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Scope(org.keycloak.authorization.model.Scope) Permission(org.keycloak.representations.idm.authorization.Permission) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) DecisionStrategy(org.keycloak.representations.idm.authorization.DecisionStrategy) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Policy(org.keycloak.authorization.model.Policy) List(java.util.List) Map(java.util.Map) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) LinkedHashSet(java.util.LinkedHashSet) Resource(org.keycloak.authorization.model.Resource) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore)

Example 45 with Resource

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

the class AuthorizationProvider method createPolicyWrapper.

private PolicyStore createPolicyWrapper(StoreFactory storeFactory) {
    return new PolicyStore() {

        PolicyStore policyStore = storeFactory.getPolicyStore();

        @Override
        public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
            Set<String> resources = representation.getResources();
            if (resources != null) {
                representation.setResources(resources.stream().map(id -> {
                    Resource resource = storeFactory.getResourceStore().findById(id, resourceServer.getId());
                    if (resource == null) {
                        resource = storeFactory.getResourceStore().findByName(id, resourceServer.getId());
                    }
                    if (resource == null) {
                        throw new RuntimeException("Resource [" + id + "] does not exist or is not owned by the resource server.");
                    }
                    return resource.getId();
                }).collect(Collectors.toSet()));
            }
            Set<String> scopes = representation.getScopes();
            if (scopes != null) {
                representation.setScopes(scopes.stream().map(id -> {
                    Scope scope = storeFactory.getScopeStore().findById(id, resourceServer.getId());
                    if (scope == null) {
                        scope = storeFactory.getScopeStore().findByName(id, resourceServer.getId());
                    }
                    if (scope == null) {
                        throw new RuntimeException("Scope [" + id + "] does not exist");
                    }
                    return scope.getId();
                }).collect(Collectors.toSet()));
            }
            Set<String> policies = representation.getPolicies();
            if (policies != null) {
                representation.setPolicies(policies.stream().map(id -> {
                    Policy policy = storeFactory.getPolicyStore().findById(id, resourceServer.getId());
                    if (policy == null) {
                        policy = storeFactory.getPolicyStore().findByName(id, resourceServer.getId());
                    }
                    if (policy == null) {
                        throw new RuntimeException("Policy [" + id + "] does not exist");
                    }
                    return policy.getId();
                }).collect(Collectors.toSet()));
            }
            return RepresentationToModel.toModel(representation, AuthorizationProvider.this, policyStore.create(representation, resourceServer));
        }

        @Override
        public void delete(String id) {
            Policy policy = findById(id, null);
            if (policy != null) {
                ResourceServer resourceServer = policy.getResourceServer();
                // if uma policy (owned by a user) also remove associated policies
                if (policy.getOwner() != null) {
                    for (Policy associatedPolicy : policy.getAssociatedPolicies()) {
                        // only remove associated policies created from the policy being deleted
                        if (associatedPolicy.getOwner() != null) {
                            policy.removeAssociatedPolicy(associatedPolicy);
                            policyStore.delete(associatedPolicy.getId());
                        }
                    }
                }
                findDependentPolicies(policy.getId(), resourceServer.getId()).forEach(dependentPolicy -> {
                    dependentPolicy.removeAssociatedPolicy(policy);
                    if (dependentPolicy.getAssociatedPolicies().isEmpty()) {
                        delete(dependentPolicy.getId());
                    }
                });
                policyStore.delete(id);
            }
        }

        @Override
        public Policy findById(String id, String resourceServerId) {
            return policyStore.findById(id, resourceServerId);
        }

        @Override
        public Policy findByName(String name, String resourceServerId) {
            return policyStore.findByName(name, resourceServerId);
        }

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

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

        @Override
        public List<Policy> findByResource(String resourceId, String resourceServerId) {
            return policyStore.findByResource(resourceId, resourceServerId);
        }

        @Override
        public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
            policyStore.findByResource(resourceId, resourceServerId, consumer);
        }

        @Override
        public List<Policy> findByResourceType(String resourceType, String resourceServerId) {
            return policyStore.findByResourceType(resourceType, resourceServerId);
        }

        @Override
        public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
            return policyStore.findByScopeIds(scopeIds, resourceServerId);
        }

        @Override
        public List<Policy> findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId) {
            return policyStore.findByScopeIds(scopeIds, resourceId, resourceServerId);
        }

        @Override
        public void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer) {
            policyStore.findByScopeIds(scopeIds, resourceId, resourceServerId, consumer);
        }

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

        @Override
        public List<Policy> findDependentPolicies(String id, String resourceServerId) {
            return policyStore.findDependentPolicies(id, resourceServerId);
        }

        @Override
        public void findByResourceType(String type, String id, Consumer<Policy> policyConsumer) {
            policyStore.findByResourceType(type, id, policyConsumer);
        }
    };
}
Also used : AbstractPolicyRepresentation(org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation) Policy(org.keycloak.authorization.model.Policy) Scope(org.keycloak.authorization.model.Scope) Consumer(java.util.function.Consumer) Resource(org.keycloak.authorization.model.Resource) PolicyStore(org.keycloak.authorization.store.PolicyStore) List(java.util.List) ResourceServer(org.keycloak.authorization.model.ResourceServer) Map(java.util.Map)

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