Search in sources :

Example 46 with Permission

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

the class AuthorizationTokenService method createPermissions.

private Collection<ResourcePermission> createPermissions(PermissionTicketToken ticket, KeycloakAuthorizationRequest request, ResourceServer resourceServer, AuthorizationProvider authorization, EvaluationContext context) {
    KeycloakIdentity identity = (KeycloakIdentity) context.getIdentity();
    StoreFactory storeFactory = authorization.getStoreFactory();
    Map<String, ResourcePermission> permissionsToEvaluate = new LinkedHashMap<>();
    ResourceStore resourceStore = storeFactory.getResourceStore();
    ScopeStore scopeStore = storeFactory.getScopeStore();
    Metadata metadata = request.getMetadata();
    final AtomicInteger limit = metadata != null && metadata.getLimit() != null ? new AtomicInteger(metadata.getLimit()) : null;
    for (Permission permission : ticket.getPermissions()) {
        if (limit != null && limit.get() <= 0) {
            break;
        }
        Set<Scope> requestedScopesModel = resolveRequestedScopes(request, resourceServer, scopeStore, permission);
        String resourceId = permission.getResourceId();
        if (resourceId != null) {
            resolveResourcePermission(request, resourceServer, identity, authorization, storeFactory, permissionsToEvaluate, resourceStore, limit, permission, requestedScopesModel, resourceId);
        } else {
            resolveScopePermissions(request, resourceServer, authorization, permissionsToEvaluate, resourceStore, limit, requestedScopesModel);
        }
    }
    resolvePreviousGrantedPermissions(ticket, request, resourceServer, permissionsToEvaluate, resourceStore, scopeStore, limit);
    return permissionsToEvaluate.values();
}
Also used : Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) ScopeStore(org.keycloak.authorization.store.ScopeStore) ResourceStore(org.keycloak.authorization.store.ResourceStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) LinkedHashMap(java.util.LinkedHashMap) Scope(org.keycloak.authorization.model.Scope) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Permission(org.keycloak.representations.idm.authorization.Permission) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 47 with Permission

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

the class AbstractPermissionService method verifyRequestedResource.

private List<Permission> verifyRequestedResource(List<PermissionRequest> request) {
    ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
    List<Permission> requestedResources = new ArrayList<>();
    for (PermissionRequest permissionRequest : request) {
        String resourceSetId = permissionRequest.getResourceId();
        List<Resource> resources = new ArrayList<>();
        if (resourceSetId == null) {
            if (permissionRequest.getScopes() == null || permissionRequest.getScopes().isEmpty()) {
                throw new ErrorResponseException("invalid_resource_id", "Resource id or name not provided.", Response.Status.BAD_REQUEST);
            }
        } else {
            Resource resource = resourceStore.findById(resourceSetId, resourceServer.getId());
            if (resource != null) {
                resources.add(resource);
            } else {
                Resource userResource = resourceStore.findByName(resourceSetId, identity.getId(), this.resourceServer.getId());
                if (userResource != null) {
                    resources.add(userResource);
                }
                if (!identity.isResourceServer()) {
                    Resource serverResource = resourceStore.findByName(resourceSetId, this.resourceServer.getId());
                    if (serverResource != null) {
                        resources.add(serverResource);
                    }
                }
            }
            if (resources.isEmpty()) {
                throw new ErrorResponseException("invalid_resource_id", "Resource set with id [" + resourceSetId + "] does not exists in this server.", Response.Status.BAD_REQUEST);
            }
        }
        if (resources.isEmpty()) {
            requestedResources.add(new Permission(null, verifyRequestedScopes(permissionRequest, null)));
        } else {
            for (Resource resource : resources) {
                requestedResources.add(new Permission(resource.getId(), verifyRequestedScopes(permissionRequest, resource)));
            }
        }
    }
    return requestedResources;
}
Also used : PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) Permission(org.keycloak.representations.idm.authorization.Permission) ArrayList(java.util.ArrayList) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 48 with Permission

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

the class PermissionManagementTest method assertPersistence.

private void assertPersistence(PermissionResponse response, ResourceRepresentation resource, String... scopeNames) throws Exception {
    String ticket = response.getTicket();
    assertNotNull(ticket);
    int expectedPermissions = scopeNames.length > 0 ? scopeNames.length : 1;
    List<PermissionTicketRepresentation> tickets = getAuthzClient().protection().permission().findByResource(resource.getId());
    assertEquals(expectedPermissions, tickets.size());
    PermissionTicketToken token = new JWSInput(ticket).readJsonContent(PermissionTicketToken.class);
    List<Permission> tokenPermissions = token.getPermissions();
    assertNotNull(tokenPermissions);
    assertEquals(expectedPermissions, scopeNames.length > 0 ? scopeNames.length : tokenPermissions.size());
    Iterator<Permission> permissionIterator = tokenPermissions.iterator();
    while (permissionIterator.hasNext()) {
        Permission resourcePermission = permissionIterator.next();
        long count = tickets.stream().filter(representation -> representation.getResource().equals(resourcePermission.getResourceId())).count();
        if (count == (scopeNames.length > 0 ? scopeNames.length : 1)) {
            permissionIterator.remove();
        }
    }
    assertTrue(tokenPermissions.isEmpty());
    ArrayList<PermissionTicketRepresentation> expectedTickets = new ArrayList<>(tickets);
    Iterator<PermissionTicketRepresentation> ticketIterator = expectedTickets.iterator();
    while (ticketIterator.hasNext()) {
        PermissionTicketRepresentation ticketRep = ticketIterator.next();
        assertFalse(ticketRep.isGranted());
        if (ticketRep.getScope() != null) {
            ScopeRepresentation scope = getClient(getRealm()).authorization().scopes().scope(ticketRep.getScope()).toRepresentation();
            if (Arrays.asList(scopeNames).contains(scope.getName())) {
                ticketIterator.remove();
            }
        } else if (ticketRep.getResource().equals(resource.getId())) {
            ticketIterator.remove();
        }
    }
    assertTrue(expectedTickets.isEmpty());
}
Also used : Arrays(java.util.Arrays) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Permission(org.keycloak.representations.idm.authorization.Permission) Matchers.not(org.hamcrest.Matchers.not) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthzClient(org.keycloak.authorization.client.AuthzClient) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) HashSet(java.util.HashSet) Assert.fail(org.junit.Assert.fail) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthServer(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer) ResourceScopesResource(org.keycloak.admin.client.resource.ResourceScopesResource) JWSInput(org.keycloak.jose.jws.JWSInput) Matchers.empty(org.hamcrest.Matchers.empty) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Iterator(java.util.Iterator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Collectors(java.util.stream.Collectors) PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) List(java.util.List) Matchers.hasItem(org.hamcrest.Matchers.hasItem) Assert.assertFalse(org.junit.Assert.assertFalse) Matchers.is(org.hamcrest.Matchers.is) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) ArrayList(java.util.ArrayList) JWSInput(org.keycloak.jose.jws.JWSInput) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) Permission(org.keycloak.representations.idm.authorization.Permission) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation)

Example 49 with Permission

use of org.keycloak.representations.idm.authorization.Permission 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)

Example 50 with Permission

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

the class ConflictingScopePermissionTest method testWithDisabledMode.

@Test
public void testWithDisabledMode() throws Exception {
    ClientResource client = getClient(getRealm());
    AuthorizationResource authorization = client.authorization();
    ResourceServerRepresentation settings = authorization.getSettings();
    settings.setPolicyEnforcementMode(PolicyEnforcementMode.DISABLED);
    settings.setDecisionStrategy(DecisionStrategy.UNANIMOUS);
    authorization.update(settings);
    Collection<Permission> permissions = getEntitlements("marta", "password");
    assertEquals(3, permissions.size());
    for (Permission permission : new ArrayList<>(permissions)) {
        String resourceSetName = permission.getResourceName();
        switch(resourceSetName) {
            case "Resource A":
                assertThat(permission.getScopes(), containsInAnyOrder("execute", "write", "read"));
                permissions.remove(permission);
                break;
            case "Resource C":
                assertThat(permission.getScopes(), containsInAnyOrder("execute", "write", "read"));
                permissions.remove(permission);
                break;
            case "Resource B":
                assertThat(permission.getScopes(), containsInAnyOrder("execute", "write", "read"));
                permissions.remove(permission);
                break;
            default:
                fail("Unexpected permission for resource [" + resourceSetName + "]");
        }
    }
    assertTrue(permissions.isEmpty());
}
Also used : ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) Permission(org.keycloak.representations.idm.authorization.Permission) ArrayList(java.util.ArrayList) ClientResource(org.keycloak.admin.client.resource.ClientResource) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) Test(org.junit.Test)

Aggregations

Permission (org.keycloak.representations.idm.authorization.Permission)73 Test (org.junit.Test)50 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)44 AccessToken (org.keycloak.representations.AccessToken)36 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)29 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)27 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)23 AuthzClient (org.keycloak.authorization.client.AuthzClient)22 ClientResource (org.keycloak.admin.client.resource.ClientResource)20 ArrayList (java.util.ArrayList)19 ResourcePermissionRepresentation (org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation)19 OAuthClient (org.keycloak.testsuite.util.OAuthClient)15 ScopePermissionRepresentation (org.keycloak.representations.idm.authorization.ScopePermissionRepresentation)14 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)13 Response (javax.ws.rs.core.Response)12 AuthorizationDeniedException (org.keycloak.authorization.client.AuthorizationDeniedException)12 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)12 PermissionRequest (org.keycloak.representations.idm.authorization.PermissionRequest)12 PermissionResponse (org.keycloak.representations.idm.authorization.PermissionResponse)12 Authorization (org.keycloak.representations.AccessToken.Authorization)11