Search in sources :

Example 46 with PolicyRepresentation

use of org.keycloak.representations.idm.authorization.PolicyRepresentation in project keycloak by keycloak.

the class AbstractBasePhotozExampleAdapterTest method printUpdatedPolicies.

protected void printUpdatedPolicies() throws FileNotFoundException {
    log.debug("Check updated policies");
    for (PolicyRepresentation policy : getAuthorizationResource().policies().policies()) {
        log.debugf("Policy: %s", policy.getName());
        for (String key : policy.getConfig().keySet()) {
            log.debugf("-- key: %s, value: %s", key, policy.getConfig().get(key));
        }
    }
    log.debug("------------------------------");
}
Also used : PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation)

Example 47 with PolicyRepresentation

use of org.keycloak.representations.idm.authorization.PolicyRepresentation 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 48 with PolicyRepresentation

use of org.keycloak.representations.idm.authorization.PolicyRepresentation in project keycloak by keycloak.

the class PolicyEvaluationResponseBuilder method toRepresentation.

private static PolicyEvaluationResponse.PolicyResultRepresentation toRepresentation(Result.PolicyResult result, AuthorizationProvider authorization) {
    PolicyEvaluationResponse.PolicyResultRepresentation policyResultRep = new PolicyEvaluationResponse.PolicyResultRepresentation();
    PolicyRepresentation representation = new PolicyRepresentation();
    Policy policy = result.getPolicy();
    representation.setId(policy.getId());
    representation.setName(policy.getName());
    representation.setType(policy.getType());
    representation.setDecisionStrategy(policy.getDecisionStrategy());
    representation.setDescription(policy.getDescription());
    if ("uma".equals(representation.getType())) {
        Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
        filters.put(PermissionTicket.FilterOption.POLICY_ID, policy.getId());
        List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(filters, policy.getResourceServer().getId(), -1, 1);
        if (!tickets.isEmpty()) {
            KeycloakSession keycloakSession = authorization.getKeycloakSession();
            RealmModel realm = authorization.getRealm();
            PermissionTicket ticket = tickets.get(0);
            UserModel userOwner = keycloakSession.users().getUserById(realm, ticket.getOwner());
            UserModel requester = keycloakSession.users().getUserById(realm, ticket.getRequester());
            String resourceOwner;
            if (userOwner != null) {
                resourceOwner = getUserEmailOrUserName(userOwner);
            } else {
                ClientModel clientOwner = realm.getClientById(ticket.getOwner());
                resourceOwner = clientOwner.getClientId();
            }
            representation.setDescription("Resource owner (" + resourceOwner + ") grants access to " + getUserEmailOrUserName(requester));
        } else {
            String description = representation.getDescription();
            if (description != null) {
                representation.setDescription(description + " (User-Managed Policy)");
            } else {
                representation.setDescription("User-Managed Policy");
            }
        }
    }
    representation.setResources(policy.getResources().stream().map(resource -> resource.getName()).collect(Collectors.toSet()));
    Set<String> scopeNames = policy.getScopes().stream().map(scope -> scope.getName()).collect(Collectors.toSet());
    representation.setScopes(scopeNames);
    policyResultRep.setPolicy(representation);
    if (result.getEffect() == Decision.Effect.DENY) {
        policyResultRep.setStatus(DecisionEffect.DENY);
        policyResultRep.setScopes(representation.getScopes());
    } else {
        policyResultRep.setStatus(DecisionEffect.PERMIT);
    }
    policyResultRep.setAssociatedPolicies(result.getAssociatedPolicies().stream().map(policy1 -> toRepresentation(policy1, authorization)).collect(Collectors.toList()));
    return policyResultRep;
}
Also used : Policy(org.keycloak.authorization.model.Policy) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Arrays(java.util.Arrays) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) HashMap(java.util.HashMap) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) ArrayList(java.util.ArrayList) PolicyEvaluationService(org.keycloak.authorization.admin.PolicyEvaluationService) UserModel(org.keycloak.models.UserModel) AccessToken(org.keycloak.representations.AccessToken) Map(java.util.Map) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ResourceServer(org.keycloak.authorization.model.ResourceServer) RealmModel(org.keycloak.models.RealmModel) EnumMap(java.util.EnumMap) Collection(java.util.Collection) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) Decision(org.keycloak.authorization.Decision) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) Policy(org.keycloak.authorization.model.Policy) List(java.util.List) Stream(java.util.stream.Stream) Result(org.keycloak.authorization.policy.evaluation.Result) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) DecisionEffect(org.keycloak.representations.idm.authorization.DecisionEffect) Comparator(java.util.Comparator) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) EnumMap(java.util.EnumMap)

Example 49 with PolicyRepresentation

use of org.keycloak.representations.idm.authorization.PolicyRepresentation in project keycloak by keycloak.

the class ResourceServerService method createDefaultPolicy.

private PolicyRepresentation createDefaultPolicy() {
    PolicyRepresentation defaultPolicy = new PolicyRepresentation();
    defaultPolicy.setName("Default Policy");
    defaultPolicy.setDescription("A policy that grants access only for users within this realm");
    defaultPolicy.setType("js");
    defaultPolicy.setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
    defaultPolicy.setLogic(Logic.POSITIVE);
    HashMap<String, String> defaultPolicyConfig = new HashMap<>();
    defaultPolicyConfig.put("code", "// by default, grants any permission associated with this policy\n$evaluation.grant();\n");
    defaultPolicy.setConfig(defaultPolicyConfig);
    session.setAttribute("ALLOW_CREATE_POLICY", true);
    getPolicyResource().create(defaultPolicy);
    return defaultPolicy;
}
Also used : PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) HashMap(java.util.HashMap)

Example 50 with PolicyRepresentation

use of org.keycloak.representations.idm.authorization.PolicyRepresentation in project keycloak by keycloak.

the class ScopeService method getPermissions.

@Path("{id}/permissions")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Response getPermissions(@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();
    }
    PolicyStore policyStore = storeFactory.getPolicyStore();
    return Response.ok(policyStore.findByScopeIds(Arrays.asList(model.getId()), resourceServer.getId()).stream().map(policy -> {
        PolicyRepresentation representation = new PolicyRepresentation();
        representation.setId(policy.getId());
        representation.setName(policy.getName());
        representation.setType(policy.getType());
        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) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) Scope(org.keycloak.authorization.model.Scope) PolicyStore(org.keycloak.authorization.store.PolicyStore) 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)

Aggregations

PolicyRepresentation (org.keycloak.representations.idm.authorization.PolicyRepresentation)58 Test (org.junit.Test)26 HashMap (java.util.HashMap)20 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)19 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)18 Response (javax.ws.rs.core.Response)15 List (java.util.List)12 Map (java.util.Map)12 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 Collectors (java.util.stream.Collectors)10 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)10 AbstractPolicyRepresentation (org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation)10 ScopeRepresentation (org.keycloak.representations.idm.authorization.ScopeRepresentation)10 UserPolicyRepresentation (org.keycloak.representations.idm.authorization.UserPolicyRepresentation)10 WebElement (org.openqa.selenium.WebElement)10 Set (java.util.Set)9 Policy (org.keycloak.authorization.model.Policy)9 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)9 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)8