Search in sources :

Example 6 with ScopeRepresentation

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

the class ScopeManagementTest method testDeleteAndPolicyUpdate.

@Test(expected = NotFoundException.class)
public void testDeleteAndPolicyUpdate() {
    ResourceScopeResource scopeResource = createDefaultScope();
    ScopeRepresentation scopeRepresentation = scopeResource.toRepresentation();
    ScopePermissionRepresentation representation = new ScopePermissionRepresentation();
    representation.setName(scopeRepresentation.getName());
    representation.addScope(scopeRepresentation.getId());
    getClientResource().authorization().permissions().scope().create(representation);
    ScopePermissionRepresentation permissionRepresentation = getClientResource().authorization().permissions().scope().findByName(scopeRepresentation.getName());
    List<ScopeRepresentation> scopes = getClientResource().authorization().policies().policy(permissionRepresentation.getId()).scopes();
    assertEquals(1, scopes.size());
    scopeResource.remove();
    assertTrue(getClientResource().authorization().policies().policy(permissionRepresentation.getId()).scopes().isEmpty());
}
Also used : ResourceScopeResource(org.keycloak.admin.client.resource.ResourceScopeResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Example 7 with ScopeRepresentation

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

the class PolicyEnforcerTest method createResource.

private ResourceRepresentation createResource(ClientResource clientResource, String name, String uri, String... scopes) {
    ResourceRepresentation representation = new ResourceRepresentation();
    representation.setName(name);
    representation.setUri(uri);
    representation.setScopes(Arrays.asList(scopes).stream().map(ScopeRepresentation::new).collect(Collectors.toSet()));
    javax.ws.rs.core.Response response = clientResource.authorization().resources().create(representation);
    representation.setId(response.readEntity(ResourceRepresentation.class).getId());
    response.close();
    return representation;
}
Also used : ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Example 8 with ScopeRepresentation

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

the class RepresentationToModel method toModel.

public static ResourceServer toModel(ResourceServerRepresentation rep, AuthorizationProvider authorization, ClientModel client) {
    ResourceServerStore resourceServerStore = authorization.getStoreFactory().getResourceServerStore();
    ResourceServer resourceServer;
    ResourceServer existing = resourceServerStore.findByClient(client);
    if (existing == null) {
        resourceServer = resourceServerStore.create(client);
        resourceServer.setAllowRemoteResourceManagement(true);
        resourceServer.setPolicyEnforcementMode(PolicyEnforcementMode.ENFORCING);
    } else {
        resourceServer = existing;
    }
    resourceServer.setPolicyEnforcementMode(rep.getPolicyEnforcementMode());
    resourceServer.setAllowRemoteResourceManagement(rep.isAllowRemoteResourceManagement());
    DecisionStrategy decisionStrategy = rep.getDecisionStrategy();
    if (decisionStrategy == null) {
        decisionStrategy = DecisionStrategy.UNANIMOUS;
    }
    resourceServer.setDecisionStrategy(decisionStrategy);
    for (ScopeRepresentation scope : rep.getScopes()) {
        toModel(scope, resourceServer, authorization);
    }
    KeycloakSession session = authorization.getKeycloakSession();
    RealmModel realm = authorization.getRealm();
    for (ResourceRepresentation resource : rep.getResources()) {
        ResourceOwnerRepresentation owner = resource.getOwner();
        if (owner == null) {
            owner = new ResourceOwnerRepresentation();
            owner.setId(resourceServer.getId());
            resource.setOwner(owner);
        } else if (owner.getName() != null) {
            UserModel user = session.users().getUserByUsername(realm, owner.getName());
            if (user != null) {
                owner.setId(user.getId());
            }
        }
        toModel(resource, resourceServer, authorization);
    }
    importPolicies(authorization, resourceServer, rep.getPolicies(), null);
    return resourceServer;
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) KeycloakSession(org.keycloak.models.KeycloakSession) DecisionStrategy(org.keycloak.representations.idm.authorization.DecisionStrategy) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) ResourceServer(org.keycloak.authorization.model.ResourceServer) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Example 9 with ScopeRepresentation

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

the class PolicyEvaluationResponseBuilder method build.

public static PolicyEvaluationResponse build(PolicyEvaluationService.EvaluationDecisionCollector decision, ResourceServer resourceServer, AuthorizationProvider authorization, KeycloakIdentity identity) {
    PolicyEvaluationResponse response = new PolicyEvaluationResponse();
    List<PolicyEvaluationResponse.EvaluationResultRepresentation> resultsRep = new ArrayList<>();
    AccessToken accessToken = identity.getAccessToken();
    AccessToken.Authorization authorizationData = new AccessToken.Authorization();
    authorizationData.setPermissions(decision.results());
    accessToken.setAuthorization(authorizationData);
    ClientModel clientModel = authorization.getRealm().getClientById(resourceServer.getId());
    if (!accessToken.hasAudience(clientModel.getClientId())) {
        accessToken.audience(clientModel.getClientId());
    }
    response.setRpt(accessToken);
    Collection<Result> results = decision.getResults();
    if (results.stream().anyMatch(evaluationResult -> evaluationResult.getEffect().equals(Decision.Effect.DENY))) {
        response.setStatus(DecisionEffect.DENY);
    } else {
        response.setStatus(DecisionEffect.PERMIT);
    }
    for (Result result : results) {
        PolicyEvaluationResponse.EvaluationResultRepresentation rep = new PolicyEvaluationResponse.EvaluationResultRepresentation();
        if (result.getEffect() == Decision.Effect.DENY) {
            rep.setStatus(DecisionEffect.DENY);
        } else {
            rep.setStatus(DecisionEffect.PERMIT);
        }
        resultsRep.add(rep);
        if (result.getPermission().getResource() != null) {
            ResourceRepresentation resource = new ResourceRepresentation();
            resource.setId(result.getPermission().getResource().getId());
            resource.setName(result.getPermission().getResource().getName());
            rep.setResource(resource);
        } else {
            ResourceRepresentation resource = new ResourceRepresentation();
            resource.setName("Any Resource with Scopes " + result.getPermission().getScopes().stream().map(Scope::getName).collect(Collectors.toList()));
            rep.setResource(resource);
        }
        rep.setScopes(result.getPermission().getScopes().stream().map(scope -> {
            ScopeRepresentation representation = new ScopeRepresentation();
            representation.setId(scope.getId());
            representation.setName(scope.getName());
            return representation;
        }).collect(Collectors.toList()));
        List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = new ArrayList<>();
        for (Result.PolicyResult policy : result.getResults()) {
            PolicyResultRepresentation policyRep = toRepresentation(policy, authorization);
            if ("resource".equals(policy.getPolicy().getType())) {
                policyRep.getPolicy().setScopes(result.getPermission().getResource().getScopes().stream().map(Scope::getName).collect(Collectors.toSet()));
            }
            policies.add(policyRep);
        }
        rep.setPolicies(policies);
    }
    resultsRep.sort(Comparator.comparing(o -> o.getResource().getName()));
    Map<String, PolicyEvaluationResponse.EvaluationResultRepresentation> groupedResults = new HashMap<>();
    resultsRep.forEach(evaluationResultRepresentation -> {
        PolicyEvaluationResponse.EvaluationResultRepresentation result = groupedResults.get(evaluationResultRepresentation.getResource().getId());
        ResourceRepresentation resource = evaluationResultRepresentation.getResource();
        if (result == null) {
            groupedResults.put(resource.getId(), evaluationResultRepresentation);
            result = evaluationResultRepresentation;
        }
        if (result.getStatus().equals(DecisionEffect.PERMIT) || (evaluationResultRepresentation.getStatus().equals(DecisionEffect.PERMIT) && result.getStatus().equals(DecisionEffect.DENY))) {
            result.setStatus(DecisionEffect.PERMIT);
        }
        List<ScopeRepresentation> scopes = result.getScopes();
        if (DecisionEffect.PERMIT.equals(result.getStatus())) {
            result.setAllowedScopes(scopes);
        }
        if (resource.getId() != null) {
            if (!scopes.isEmpty()) {
                result.getResource().setName(evaluationResultRepresentation.getResource().getName() + " with scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
            } else {
                result.getResource().setName(evaluationResultRepresentation.getResource().getName());
            }
        } else {
            result.getResource().setName("Any Resource with Scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
        }
        List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = result.getPolicies();
        for (PolicyEvaluationResponse.PolicyResultRepresentation policy : new ArrayList<>(evaluationResultRepresentation.getPolicies())) {
            if (!policies.contains(policy)) {
                policies.add(policy);
            }
        }
    });
    response.setResults(groupedResults.values().stream().collect(Collectors.toList()));
    return response;
}
Also used : 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) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) Result(org.keycloak.authorization.policy.evaluation.Result) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ClientModel(org.keycloak.models.ClientModel) Function(java.util.function.Function) Scope(org.keycloak.authorization.model.Scope) AccessToken(org.keycloak.representations.AccessToken) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation)

Example 10 with ScopeRepresentation

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

the class PolicyEvaluationService method createPermissions.

private List<ResourcePermission> createPermissions(PolicyEvaluationRequest representation, EvaluationContext evaluationContext, AuthorizationProvider authorization, AuthorizationRequest request) {
    return representation.getResources().stream().flatMap((Function<ResourceRepresentation, Stream<ResourcePermission>>) resource -> {
        StoreFactory storeFactory = authorization.getStoreFactory();
        if (resource == null) {
            resource = new ResourceRepresentation();
        }
        Set<ScopeRepresentation> givenScopes = resource.getScopes();
        if (givenScopes == null) {
            givenScopes = new HashSet<>();
        }
        ScopeStore scopeStore = storeFactory.getScopeStore();
        Set<Scope> scopes = givenScopes.stream().map(scopeRepresentation -> scopeStore.findByName(scopeRepresentation.getName(), resourceServer.getId())).collect(Collectors.toSet());
        if (resource.getId() != null) {
            Resource resourceModel = storeFactory.getResourceStore().findById(resource.getId(), resourceServer.getId());
            return new ArrayList<>(Arrays.asList(Permissions.createResourcePermissions(resourceModel, resourceServer, scopes, authorization, request))).stream();
        } else if (resource.getType() != null) {
            return storeFactory.getResourceStore().findByType(resource.getType(), resourceServer.getId()).stream().map(resource1 -> Permissions.createResourcePermissions(resource1, resourceServer, scopes, authorization, request));
        } else {
            if (scopes.isEmpty()) {
                return Stream.empty();
            }
            List<Resource> resources = storeFactory.getResourceStore().findByScope(scopes.stream().map(Scope::getId).collect(Collectors.toList()), resourceServer.getId());
            if (resources.isEmpty()) {
                return scopes.stream().map(scope -> new ResourcePermission(null, new ArrayList<>(Arrays.asList(scope)), resourceServer));
            }
            return resources.stream().map(resource12 -> Permissions.createResourcePermissions(resource12, resourceServer, scopes, authorization, request));
        }
    }).collect(Collectors.toList());
}
Also used : ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Arrays(java.util.Arrays) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Produces(javax.ws.rs.Produces) Permissions(org.keycloak.authorization.permission.Permissions) OAuthErrorException(org.keycloak.OAuthErrorException) Consumes(javax.ws.rs.Consumes) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AccessToken(org.keycloak.representations.AccessToken) DecisionPermissionCollector(org.keycloak.authorization.policy.evaluation.DecisionPermissionCollector) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) PolicyEvaluationResponseBuilder(org.keycloak.authorization.admin.representation.PolicyEvaluationResponseBuilder) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) List(java.util.List) ScopeStore(org.keycloak.authorization.store.ScopeStore) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) DefaultEvaluationContext(org.keycloak.authorization.common.DefaultEvaluationContext) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) Attributes(org.keycloak.authorization.attribute.Attributes) Permission(org.keycloak.representations.idm.authorization.Permission) Logger(org.jboss.logging.Logger) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) TokenManager(org.keycloak.protocol.oidc.TokenManager) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) PolicyEvaluationRequest(org.keycloak.representations.idm.authorization.PolicyEvaluationRequest) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) Status(javax.ws.rs.core.Response.Status) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) UserSessionModel(org.keycloak.models.UserSessionModel) EvaluationContext(org.keycloak.authorization.policy.evaluation.EvaluationContext) Result(org.keycloak.authorization.policy.evaluation.Result) Urls(org.keycloak.services.Urls) Collections(java.util.Collections) Resource(org.keycloak.authorization.model.Resource) Resource(org.keycloak.authorization.model.Resource) ScopeStore(org.keycloak.authorization.store.ScopeStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Function(java.util.function.Function) Scope(org.keycloak.authorization.model.Scope) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) List(java.util.List) ArrayList(java.util.ArrayList) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Aggregations

ScopeRepresentation (org.keycloak.representations.idm.authorization.ScopeRepresentation)48 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)27 Test (org.junit.Test)18 ArrayList (java.util.ArrayList)14 List (java.util.List)12 Response (javax.ws.rs.core.Response)11 HashSet (java.util.HashSet)10 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)10 HashMap (java.util.HashMap)8 Map (java.util.Map)8 Set (java.util.Set)8 AuthzClient (org.keycloak.authorization.client.AuthzClient)8 Arrays (java.util.Arrays)7 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)7 PolicyRepresentation (org.keycloak.representations.idm.authorization.PolicyRepresentation)7 Collection (java.util.Collection)6 Collectors (java.util.stream.Collectors)6 ResourceScopesResource (org.keycloak.admin.client.resource.ResourceScopesResource)5 HttpResponseException (org.keycloak.authorization.client.util.HttpResponseException)5 WebElement (org.openqa.selenium.WebElement)5