Search in sources :

Example 61 with Resource

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

the class ScopeService method getResources.

@Path("{id}/resources")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Response getResources(@PathParam("id") String id) {
    this.auth.realm().requireViewAuthorization();
    StoreFactory storeFactory = this.authorization.getStoreFactory();
    Scope model = storeFactory.getScopeStore().findById(id, resourceServer.getId());
    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 -> {
        ResourceRepresentation representation = new ResourceRepresentation();
        representation.setId(resource.getId());
        representation.setName(resource.getName());
        return representation;
    }).collect(Collectors.toList())).build();
}
Also used : OperationType(org.keycloak.events.admin.OperationType) Scope(org.keycloak.authorization.model.Scope) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) PathParam(javax.ws.rs.PathParam) Arrays(java.util.Arrays) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) StoreFactory(org.keycloak.authorization.store.StoreFactory) Constants(org.keycloak.models.Constants) Path(javax.ws.rs.Path) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ModelToRepresentation.toRepresentation(org.keycloak.models.utils.ModelToRepresentation.toRepresentation) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Status(javax.ws.rs.core.Response.Status) DELETE(javax.ws.rs.DELETE) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) EnumMap(java.util.EnumMap) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) PolicyStore(org.keycloak.authorization.store.PolicyStore) Collectors(java.util.stream.Collectors) Policy(org.keycloak.authorization.model.Policy) List(java.util.List) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) RepresentationToModel.toModel(org.keycloak.models.utils.RepresentationToModel.toModel) PUT(javax.ws.rs.PUT) Resource(org.keycloak.authorization.model.Resource) ErrorResponse(org.keycloak.services.ErrorResponse) AdminEventBuilder(org.keycloak.services.resources.admin.AdminEventBuilder) Scope(org.keycloak.authorization.model.Scope) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 62 with Resource

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

the class PolicyService method findAll.

@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response findAll(@QueryParam("policyId") String id, @QueryParam("name") String name, @QueryParam("type") String type, @QueryParam("resource") String resource, @QueryParam("scope") String scope, @QueryParam("permission") Boolean permission, @QueryParam("owner") String owner, @QueryParam("fields") String fields, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResult) {
    if (auth != null) {
        this.auth.realm().requireViewAuthorization();
    }
    Map<Policy.FilterOption, String[]> search = new EnumMap<>(Policy.FilterOption.class);
    if (id != null && !"".equals(id.trim())) {
        search.put(Policy.FilterOption.ID, new String[] { id });
    }
    if (name != null && !"".equals(name.trim())) {
        search.put(Policy.FilterOption.NAME, new String[] { name });
    }
    if (type != null && !"".equals(type.trim())) {
        search.put(Policy.FilterOption.TYPE, new String[] { type });
    }
    if (owner != null && !"".equals(owner.trim())) {
        search.put(Policy.FilterOption.OWNER, new String[] { owner });
    }
    StoreFactory storeFactory = authorization.getStoreFactory();
    if (resource != null && !"".equals(resource.trim())) {
        ResourceStore resourceStore = storeFactory.getResourceStore();
        Resource resourceModel = resourceStore.findById(resource, resourceServer.getId());
        if (resourceModel == null) {
            Map<Resource.FilterOption, String[]> resourceFilters = new EnumMap<>(Resource.FilterOption.class);
            resourceFilters.put(Resource.FilterOption.NAME, new String[] { resource });
            if (owner != null) {
                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());
            if (resources.isEmpty()) {
                return Response.noContent().build();
            }
            search.put(Policy.FilterOption.RESOURCE_ID, resources.toArray(new String[resources.size()]));
        } else {
            search.put(Policy.FilterOption.RESOURCE_ID, new String[] { resourceModel.getId() });
        }
    }
    if (scope != null && !"".equals(scope.trim())) {
        ScopeStore scopeStore = storeFactory.getScopeStore();
        Scope scopeModel = scopeStore.findById(scope, resourceServer.getId());
        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());
            if (scopes.isEmpty()) {
                return Response.noContent().build();
            }
            search.put(Policy.FilterOption.SCOPE_ID, scopes.toArray(new String[scopes.size()]));
        } else {
            search.put(Policy.FilterOption.SCOPE_ID, new String[] { scopeModel.getId() });
        }
    }
    if (permission != null) {
        search.put(Policy.FilterOption.PERMISSION, new String[] { permission.toString() });
    }
    return Response.ok(doSearch(firstResult, maxResult, fields, search)).build();
}
Also used : Policy(org.keycloak.authorization.model.Policy) 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) EnumMap(java.util.EnumMap) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 63 with Resource

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

the class ResourceSetService method find.

@Path("/search")
@GET
@NoCache
@Produces("application/json")
public Response find(@QueryParam("name") String name) {
    this.auth.realm().requireViewAuthorization();
    StoreFactory storeFactory = authorization.getStoreFactory();
    if (name == null) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    Resource model = storeFactory.getResourceStore().findByName(name, this.resourceServer.getId());
    if (model == null) {
        return Response.status(Status.NO_CONTENT).build();
    }
    return Response.ok(toRepresentation(model, this.resourceServer.getId(), authorization)).build();
}
Also used : Resource(org.keycloak.authorization.model.Resource) StoreFactory(org.keycloak.authorization.store.StoreFactory) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 64 with Resource

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

the class PolicyEvaluationTest method testCheckResourceAttributes.

public static void testCheckResourceAttributes(KeycloakSession session) {
    session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
    JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
    policyRepresentation.setName("testCheckResourceAttributes");
    StringBuilder builder = new StringBuilder();
    builder.append("var permission = $evaluation.getPermission();");
    builder.append("var resource = permission.getResource();");
    builder.append("var attributes = resource.getAttributes();");
    builder.append("if (attributes.size() == 2 && attributes.containsKey('a1') && attributes.containsKey('a2') && attributes.get('a1').size() == 2 && attributes.get('a2').get(0).equals('3') && resource.getAttribute('a1').size() == 2 && resource.getSingleAttribute('a2').equals('3')) { $evaluation.grant(); }");
    policyRepresentation.setCode(builder.toString());
    Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
    PolicyProvider provider = authorization.getProvider(policy.getType());
    Resource resource = storeFactory.getResourceStore().create("testCheckResourceAttributesResource", resourceServer, resourceServer.getId());
    resource.setAttribute("a1", Arrays.asList("1", "2"));
    resource.setAttribute("a2", Arrays.asList("3"));
    DefaultEvaluation evaluation = createEvaluation(session, authorization, resource, resourceServer, policy);
    provider.evaluate(evaluation);
    Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
}
Also used : Policy(org.keycloak.authorization.model.Policy) ClientModel(org.keycloak.models.ClientModel) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) PolicyProvider(org.keycloak.authorization.policy.provider.PolicyProvider) Resource(org.keycloak.authorization.model.Resource) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceServer(org.keycloak.authorization.model.ResourceServer) DefaultEvaluation(org.keycloak.authorization.policy.evaluation.DefaultEvaluation)

Example 65 with Resource

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

the class PolicyEvaluationTest method testCachedDecisionsWithNegativePolicies.

public static void testCachedDecisionsWithNegativePolicies(KeycloakSession session) {
    session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
    Scope readScope = storeFactory.getScopeStore().create("read", resourceServer);
    Scope writeScope = storeFactory.getScopeStore().create("write", resourceServer);
    JSPolicyRepresentation policy = new JSPolicyRepresentation();
    policy.setName(KeycloakModelUtils.generateId());
    policy.setCode("$evaluation.grant()");
    policy.setLogic(Logic.NEGATIVE);
    storeFactory.getPolicyStore().create(policy, resourceServer);
    ScopePermissionRepresentation readPermission = new ScopePermissionRepresentation();
    readPermission.setName(KeycloakModelUtils.generateId());
    readPermission.addScope(readScope.getId());
    readPermission.addPolicy(policy.getName());
    storeFactory.getPolicyStore().create(readPermission, resourceServer);
    ScopePermissionRepresentation writePermission = new ScopePermissionRepresentation();
    writePermission.setName(KeycloakModelUtils.generateId());
    writePermission.addScope(writeScope.getId());
    writePermission.addPolicy(policy.getName());
    storeFactory.getPolicyStore().create(writePermission, resourceServer);
    Resource resource = storeFactory.getResourceStore().create(KeycloakModelUtils.generateId(), resourceServer, resourceServer.getId());
    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);
    Assert.assertEquals(0, permissions.size());
}
Also used : ClientModel(org.keycloak.models.ClientModel) PermissionEvaluator(org.keycloak.authorization.permission.evaluator.PermissionEvaluator) Scope(org.keycloak.authorization.model.Scope) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Resource(org.keycloak.authorization.model.Resource) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Permission(org.keycloak.representations.idm.authorization.Permission) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceServer(org.keycloak.authorization.model.ResourceServer) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation)

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