Search in sources :

Example 21 with PolicyStore

use of org.keycloak.authorization.store.PolicyStore in project keycloak by keycloak.

the class DefaultPolicyEvaluator method evaluate.

@Override
public void evaluate(ResourcePermission permission, AuthorizationProvider authorizationProvider, EvaluationContext executionContext, Decision decision, Map<Policy, Map<Object, Decision.Effect>> decisionCache) {
    StoreFactory storeFactory = authorizationProvider.getStoreFactory();
    PolicyStore policyStore = storeFactory.getPolicyStore();
    ResourceStore resourceStore = storeFactory.getResourceStore();
    ResourceServer resourceServer = permission.getResourceServer();
    PolicyEnforcementMode enforcementMode = resourceServer.getPolicyEnforcementMode();
    if (PolicyEnforcementMode.DISABLED.equals(enforcementMode)) {
        grantAndComplete(permission, authorizationProvider, executionContext, decision);
        return;
    }
    // if marked as granted we just complete the evaluation
    if (permission.isGranted()) {
        grantAndComplete(permission, authorizationProvider, executionContext, decision);
        return;
    }
    AtomicBoolean verified = new AtomicBoolean();
    Consumer<Policy> policyConsumer = createPolicyEvaluator(permission, authorizationProvider, executionContext, decision, verified, decisionCache);
    Resource resource = permission.getResource();
    if (resource != null) {
        policyStore.findByResource(resource.getId(), resourceServer.getId(), policyConsumer);
        if (resource.getType() != null) {
            policyStore.findByResourceType(resource.getType(), resourceServer.getId(), policyConsumer);
            if (!resource.getOwner().equals(resourceServer.getId())) {
                for (Resource typedResource : resourceStore.findByType(resource.getType(), resourceServer.getId())) {
                    policyStore.findByResource(typedResource.getId(), resourceServer.getId(), policyConsumer);
                }
            }
        }
    }
    Collection<Scope> scopes = permission.getScopes();
    if (!scopes.isEmpty()) {
        policyStore.findByScopeIds(scopes.stream().map(Scope::getId).collect(Collectors.toList()), null, resourceServer.getId(), policyConsumer);
    }
    if (verified.get()) {
        decision.onComplete(permission);
        return;
    }
    if (PolicyEnforcementMode.PERMISSIVE.equals(enforcementMode)) {
        grantAndComplete(permission, authorizationProvider, executionContext, decision);
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Scope(org.keycloak.authorization.model.Scope) Resource(org.keycloak.authorization.model.Resource) PolicyStore(org.keycloak.authorization.store.PolicyStore) ResourceStore(org.keycloak.authorization.store.ResourceStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceServer(org.keycloak.authorization.model.ResourceServer) PolicyEnforcementMode(org.keycloak.representations.idm.authorization.PolicyEnforcementMode)

Example 22 with PolicyStore

use of org.keycloak.authorization.store.PolicyStore in project keycloak by keycloak.

the class ExportUtils method exportAuthorizationSettings.

public static ResourceServerRepresentation exportAuthorizationSettings(KeycloakSession session, ClientModel client) {
    AuthorizationProviderFactory providerFactory = (AuthorizationProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(AuthorizationProvider.class);
    AuthorizationProvider authorization = providerFactory.create(session, client.getRealm());
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServer settingsModel = authorization.getStoreFactory().getResourceServerStore().findByClient(client);
    if (settingsModel == null) {
        return null;
    }
    ResourceServerRepresentation representation = toRepresentation(settingsModel, client);
    representation.setId(null);
    representation.setName(null);
    representation.setClientId(null);
    List<ResourceRepresentation> resources = storeFactory.getResourceStore().findByResourceServer(settingsModel.getId()).stream().map(resource -> {
        ResourceRepresentation rep = toRepresentation(resource, settingsModel.getId(), authorization);
        if (rep.getOwner().getId().equals(settingsModel.getId())) {
            rep.setOwner((ResourceOwnerRepresentation) null);
        } else {
            rep.getOwner().setId(null);
        }
        rep.getScopes().forEach(scopeRepresentation -> {
            scopeRepresentation.setId(null);
            scopeRepresentation.setIconUri(null);
        });
        return rep;
    }).collect(Collectors.toList());
    representation.setResources(resources);
    List<PolicyRepresentation> policies = new ArrayList<>();
    PolicyStore policyStore = storeFactory.getPolicyStore();
    policies.addAll(policyStore.findByResourceServer(settingsModel.getId()).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()).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 -> {
        ScopeRepresentation rep = toRepresentation(scope);
        rep.setPolicies(null);
        rep.setResources(null);
        return rep;
    }).collect(Collectors.toList());
    representation.setScopes(scopes);
    return representation;
}
Also used : 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) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ArrayList(java.util.ArrayList) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) AuthorizationProviderFactory(org.keycloak.authorization.AuthorizationProviderFactory) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) PolicyStore(org.keycloak.authorization.store.PolicyStore) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 23 with PolicyStore

use of org.keycloak.authorization.store.PolicyStore in project keycloak by keycloak.

the class AccountFormService method grantPermission.

@Path("resource/{resource_id}/grant")
@POST
public Response grantPermission(@PathParam("resource_id") String resourceId, @FormParam("action") String action, @FormParam("permission_id") String[] permissionId, @FormParam("requester") String requester) {
    MultivaluedMap<String, String> formData = request.getDecodedFormParameters();
    if (auth == null) {
        return login("resource");
    }
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    csrfCheck(formData);
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
    Resource resource = authorization.getStoreFactory().getResourceStore().findById(resourceId, null);
    if (resource == null) {
        return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
    }
    if (action == null) {
        return ErrorResponse.error("Invalid action", Response.Status.BAD_REQUEST);
    }
    boolean isGrant = "grant".equals(action);
    boolean isDeny = "deny".equals(action);
    boolean isRevoke = "revoke".equals(action);
    boolean isRevokePolicy = "revokePolicy".equals(action);
    boolean isRevokePolicyAll = "revokePolicyAll".equals(action);
    if (isRevokePolicy || isRevokePolicyAll) {
        List<String> ids = new ArrayList<>(Arrays.asList(permissionId));
        Iterator<String> iterator = ids.iterator();
        PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
        Policy policy = null;
        while (iterator.hasNext()) {
            String id = iterator.next();
            if (!id.contains(":")) {
                policy = policyStore.findById(id, client.getId());
                iterator.remove();
                break;
            }
        }
        Set<Scope> scopesToKeep = new HashSet<>();
        if (isRevokePolicyAll) {
            for (Scope scope : policy.getScopes()) {
                policy.removeScope(scope);
            }
        } else {
            for (String id : ids) {
                scopesToKeep.add(authorization.getStoreFactory().getScopeStore().findById(id.split(":")[1], client.getId()));
            }
            for (Scope scope : policy.getScopes()) {
                if (!scopesToKeep.contains(scope)) {
                    policy.removeScope(scope);
                }
            }
        }
        if (policy.getScopes().isEmpty()) {
            for (Policy associated : policy.getAssociatedPolicies()) {
                policyStore.delete(associated.getId());
            }
            policyStore.delete(policy.getId());
        }
    } else {
        Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
        filters.put(PermissionTicket.FilterOption.RESOURCE_ID, resource.getId());
        filters.put(PermissionTicket.FilterOption.REQUESTER, session.users().getUserByUsername(realm, requester).getId());
        if (isRevoke) {
            filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.TRUE.toString());
        } else {
            filters.put(PermissionTicket.FilterOption.GRANTED, Boolean.FALSE.toString());
        }
        List<PermissionTicket> tickets = ticketStore.find(filters, resource.getResourceServer(), -1, -1);
        Iterator<PermissionTicket> iterator = tickets.iterator();
        while (iterator.hasNext()) {
            PermissionTicket ticket = iterator.next();
            if (isGrant) {
                if (permissionId != null && permissionId.length > 0 && !Arrays.asList(permissionId).contains(ticket.getId())) {
                    continue;
                }
            }
            if (isGrant && !ticket.isGranted()) {
                ticket.setGrantedTimestamp(System.currentTimeMillis());
                iterator.remove();
            } else if (isDeny || isRevoke) {
                if (permissionId != null && permissionId.length > 0 && Arrays.asList(permissionId).contains(ticket.getId())) {
                    iterator.remove();
                }
            }
        }
        for (PermissionTicket ticket : tickets) {
            ticketStore.delete(ticket.getId());
        }
    }
    if (isRevoke || isRevokePolicy || isRevokePolicyAll) {
        return forwardToPage("resource", AccountPages.RESOURCE_DETAIL);
    }
    return forwardToPage("resource", AccountPages.RESOURCES);
}
Also used : OTPPolicy(org.keycloak.models.OTPPolicy) Policy(org.keycloak.authorization.model.Policy) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) RealmsResource(org.keycloak.services.resources.RealmsResource) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) Scope(org.keycloak.authorization.model.Scope) PermissionTicketStore(org.keycloak.authorization.store.PermissionTicketStore) PolicyStore(org.keycloak.authorization.store.PolicyStore) EnumMap(java.util.EnumMap) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 24 with PolicyStore

use of org.keycloak.authorization.store.PolicyStore in project keycloak by keycloak.

the class ResourceSetService method getPermissions.

@Path("{id}/permissions")
@GET
@NoCache
@Produces("application/json")
public Response getPermissions(@PathParam("id") String id) {
    requireView();
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceStore resourceStore = storeFactory.getResourceStore();
    Resource model = resourceStore.findById(id, resourceServer.getId());
    if (model == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
    Set<Policy> policies = new HashSet<>();
    policies.addAll(policyStore.findByResource(model.getId(), resourceServer.getId()));
    if (model.getType() != null) {
        policies.addAll(policyStore.findByResourceType(model.getType(), resourceServer.getId()));
        Map<Resource.FilterOption, String[]> resourceFilter = new EnumMap<>(Resource.FilterOption.class);
        resourceFilter.put(Resource.FilterOption.OWNER, new String[] { resourceServer.getId() });
        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()));
        }
    }
    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()));
    List<PolicyRepresentation> representation = new ArrayList<>();
    for (Policy policyModel : policies) {
        if (!"uma".equalsIgnoreCase(policyModel.getType())) {
            PolicyRepresentation policy = new PolicyRepresentation();
            policy.setId(policyModel.getId());
            policy.setName(policyModel.getName());
            policy.setType(policyModel.getType());
            if (!representation.contains(policy)) {
                representation.add(policy);
            }
        }
    }
    return Response.ok(representation).build();
}
Also used : Policy(org.keycloak.authorization.model.Policy) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) BiFunction(java.util.function.BiFunction) Path(javax.ws.rs.Path) OAuthErrorException(org.keycloak.OAuthErrorException) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ErrorResponseException(org.keycloak.services.ErrorResponseException) ModelToRepresentation.toRepresentation(org.keycloak.models.utils.ModelToRepresentation.toRepresentation) Map(java.util.Map) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) EnumMap(java.util.EnumMap) Collection(java.util.Collection) Set(java.util.Set) PolicyStore(org.keycloak.authorization.store.PolicyStore) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) RepresentationToModel.toModel(org.keycloak.models.utils.RepresentationToModel.toModel) ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) PathParam(javax.ws.rs.PathParam) Scope(org.keycloak.authorization.model.Scope) GET(javax.ws.rs.GET) StoreFactory(org.keycloak.authorization.store.StoreFactory) Constants(org.keycloak.models.Constants) HashMap(java.util.HashMap) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) Status(javax.ws.rs.core.Response.Status) PathMatcher(org.keycloak.common.util.PathMatcher) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) Policy(org.keycloak.authorization.model.Policy) NoCache(org.jboss.resteasy.annotations.cache.NoCache) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) Resource(org.keycloak.authorization.model.Resource) AdminEventBuilder(org.keycloak.services.resources.admin.AdminEventBuilder) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) ResourceStore(org.keycloak.authorization.store.ResourceStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) PolicyStore(org.keycloak.authorization.store.PolicyStore) EnumMap(java.util.EnumMap) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 25 with PolicyStore

use of org.keycloak.authorization.store.PolicyStore in project keycloak by keycloak.

the class PolicyResourceService method delete.

@DELETE
public Response delete() {
    if (auth != null) {
        this.auth.realm().requireManageAuthorization();
    }
    if (policy == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    StoreFactory storeFactory = authorization.getStoreFactory();
    PolicyStore policyStore = storeFactory.getPolicyStore();
    PolicyProviderFactory resource = getProviderFactory(policy.getType());
    if (resource != null) {
        resource.onRemove(policy, authorization);
    }
    policyStore.delete(policy.getId());
    audit(toRepresentation(policy, authorization), OperationType.DELETE);
    return Response.noContent().build();
}
Also used : PolicyProviderFactory(org.keycloak.authorization.policy.provider.PolicyProviderFactory) PolicyStore(org.keycloak.authorization.store.PolicyStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) DELETE(javax.ws.rs.DELETE)

Aggregations

PolicyStore (org.keycloak.authorization.store.PolicyStore)28 Policy (org.keycloak.authorization.model.Policy)20 StoreFactory (org.keycloak.authorization.store.StoreFactory)16 ResourceServer (org.keycloak.authorization.model.ResourceServer)11 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)10 Resource (org.keycloak.authorization.model.Resource)10 Scope (org.keycloak.authorization.model.Scope)10 List (java.util.List)9 Map (java.util.Map)9 ArrayList (java.util.ArrayList)7 HashSet (java.util.HashSet)7 EnumMap (java.util.EnumMap)6 ResourceStore (org.keycloak.authorization.store.ResourceStore)6 KeycloakSession (org.keycloak.models.KeycloakSession)5 PolicyRepresentation (org.keycloak.representations.idm.authorization.PolicyRepresentation)5 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 LinkedList (java.util.LinkedList)4 Set (java.util.Set)4 Collectors (java.util.stream.Collectors)4