Search in sources :

Example 31 with ScopeRepresentation

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

the class AlbumService method createProtectedResource.

private void createProtectedResource(Album album) {
    log.debug("Creating ProtectedResource for " + album);
    try {
        HashSet<ScopeRepresentation> scopes = new HashSet<>();
        scopes.add(new ScopeRepresentation(SCOPE_ALBUM_VIEW));
        scopes.add(new ScopeRepresentation(SCOPE_ALBUM_DELETE));
        ResourceRepresentation albumResource = new ResourceRepresentation(album.getName(), scopes, "/album/" + album.getName(), "http://photoz.com/album");
        albumResource.setOwner(album.getUserId());
        if (album.isUserManaged()) {
            albumResource.setOwnerManagedAccess(true);
        }
        getAuthzClient().protection().resource().create(albumResource);
    } catch (Exception e) {
        throw new RuntimeException("Could not register protected resource.", e);
    }
}
Also used : ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) HashSet(java.util.HashSet) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Example 32 with ScopeRepresentation

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

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

the class PermissionManagementTest method testDeleteScopeAndPermissionTicket.

@Test
public void testDeleteScopeAndPermissionTicket() throws Exception {
    ResourceRepresentation resource = addResource("Resource A", "kolo", true, "ScopeA", "ScopeB", "ScopeC");
    PermissionRequest permissionRequest = new PermissionRequest(resource.getId());
    permissionRequest.setScopes(new HashSet<>(Arrays.asList("ScopeA", "ScopeB", "ScopeC")));
    AuthzClient authzClient = getAuthzClient();
    PermissionResponse response = authzClient.protection("marta", "password").permission().create(permissionRequest);
    assertNotNull(response.getTicket());
    AuthorizationRequest request = new AuthorizationRequest();
    request.setTicket(response.getTicket());
    request.setClaimToken(authzClient.obtainAccessToken("marta", "password").getToken());
    try {
        authzClient.authorization().authorize(request);
    } catch (Exception e) {
    }
    assertEquals(3, authzClient.protection().permission().findByResource(resource.getId()).size());
    AuthorizationResource authorization = getClient(getRealm()).authorization();
    ResourceScopesResource scopes = authorization.scopes();
    ScopeRepresentation scope = scopes.findByName("ScopeA");
    List permissions = authzClient.protection().permission().findByScope(scope.getId());
    assertFalse(permissions.isEmpty());
    assertEquals(1, permissions.size());
    resource.setScopes(Collections.emptySet());
    authorization.resources().resource(resource.getId()).update(resource);
    scopes.scope(scope.getId()).remove();
    assertTrue(authzClient.protection().permission().findByScope(scope.getId()).isEmpty());
    assertEquals(0, authzClient.protection().permission().findByResource(resource.getId()).size());
}
Also used : PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) AuthzClient(org.keycloak.authorization.client.AuthzClient) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) ResourceScopesResource(org.keycloak.admin.client.resource.ResourceScopesResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ArrayList(java.util.ArrayList) List(java.util.List) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Test(org.junit.Test)

Example 34 with ScopeRepresentation

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

the class ExportImportUtil method assertAuthorizationSettingsTestAppAuthz.

private static void assertAuthorizationSettingsTestAppAuthz(RealmResource realmRsc) {
    AuthorizationResource authzResource = ApiUtil.findAuthorizationSettings(realmRsc, "test-app-authz");
    Assert.assertNotNull(authzResource);
    List<ResourceRepresentation> resources = authzResource.resources().resources();
    Assert.assertEquals(4, resources.size());
    ResourceServerRepresentation authzSettings = authzResource.getSettings();
    List<Predicate<ResourceRepresentation>> resourcePredicates = new ArrayList<>();
    resourcePredicates.add(resourceRep -> {
        if ("Admin Resource".equals(resourceRep.getName())) {
            Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId());
            Assert.assertEquals("/protected/admin/*", resourceRep.getUri());
            Assert.assertEquals("http://test-app-authz/protected/admin", resourceRep.getType());
            Assert.assertEquals("http://icons.com/icon-admin", resourceRep.getIconUri());
            Assert.assertEquals(1, resourceRep.getScopes().size());
            return true;
        }
        return false;
    });
    resourcePredicates.add(resourceRep -> {
        if ("Protected Resource".equals(resourceRep.getName())) {
            Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId());
            Assert.assertEquals("/*", resourceRep.getUri());
            Assert.assertEquals("http://test-app-authz/protected/resource", resourceRep.getType());
            Assert.assertEquals("http://icons.com/icon-resource", resourceRep.getIconUri());
            Assert.assertEquals(1, resourceRep.getScopes().size());
            return true;
        }
        return false;
    });
    resourcePredicates.add(resourceRep -> {
        if ("Premium Resource".equals(resourceRep.getName())) {
            Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId());
            Assert.assertEquals("/protected/premium/*", resourceRep.getUri());
            Assert.assertEquals("urn:test-app-authz:protected:resource", resourceRep.getType());
            Assert.assertEquals("http://icons.com/icon-premium", resourceRep.getIconUri());
            Assert.assertEquals(1, resourceRep.getScopes().size());
            return true;
        }
        return false;
    });
    resourcePredicates.add(resourceRep -> {
        if ("Main Page".equals(resourceRep.getName())) {
            Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId());
            Assert.assertNull(resourceRep.getUri());
            Assert.assertEquals("urn:test-app-authz:protected:resource", resourceRep.getType());
            Assert.assertEquals("http://icons.com/icon-main-page", resourceRep.getIconUri());
            Assert.assertEquals(3, resourceRep.getScopes().size());
            return true;
        }
        return false;
    });
    assertPredicate(resources, resourcePredicates);
    List<ScopeRepresentation> scopes = authzResource.scopes().scopes();
    Assert.assertEquals(6, scopes.size());
    List<Predicate<ScopeRepresentation>> scopePredicates = new ArrayList<>();
    scopePredicates.add(scopeRepresentation -> "admin-access".equals(scopeRepresentation.getName()));
    scopePredicates.add(scopeRepresentation -> "resource-access".equals(scopeRepresentation.getName()));
    scopePredicates.add(scopeRepresentation -> "premium-access".equals(scopeRepresentation.getName()));
    scopePredicates.add(scopeRepresentation -> "urn:test-app-authz:page:main:actionForAdmin".equals(scopeRepresentation.getName()));
    scopePredicates.add(scopeRepresentation -> "urn:test-app-authz:page:main:actionForUser".equals(scopeRepresentation.getName()));
    scopePredicates.add(scopeRepresentation -> "urn:test-app-authz:page:main:actionForPremiumUser".equals(scopeRepresentation.getName()));
    assertPredicate(scopes, scopePredicates);
    List<PolicyRepresentation> policies = authzResource.policies().policies();
    Assert.assertEquals(14, policies.size());
    List<Predicate<PolicyRepresentation>> policyPredicates = new ArrayList<>();
    policyPredicates.add(policyRepresentation -> "Any Admin Policy".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "Any User Policy".equals(policyRepresentation.getName()));
    policyPredicates.add(representation -> "Client and Realm Role Policy".equals(representation.getName()));
    policyPredicates.add(representation -> "Client Test Policy".equals(representation.getName()));
    policyPredicates.add(representation -> "Group Policy Test".equals(representation.getName()));
    policyPredicates.add(policyRepresentation -> "Only Premium User Policy".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "wburke policy".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "All Users Policy".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "Premium Resource Permission".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "Administrative Resource Permission".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "Protected Resource Permission".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "Action 1 on Main Page Resource Permission".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "Action 2 on Main Page Resource Permission".equals(policyRepresentation.getName()));
    policyPredicates.add(policyRepresentation -> "Action 3 on Main Page Resource Permission".equals(policyRepresentation.getName()));
    assertPredicate(policies, policyPredicates);
}
Also used : ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) ArrayList(java.util.ArrayList) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Predicate(java.util.function.Predicate) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation)

Example 35 with ScopeRepresentation

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

the class ResourcesRestServiceTest method testApprovePermissionRequest.

@Test
public void testApprovePermissionRequest() throws IOException {
    Resource resource = getMyResources().get(0);
    List<Permission> requests = doGet("/" + resource.getId() + "/permissions/requests", new TypeReference<List<Permission>>() {
    });
    assertTrue(requests.isEmpty());
    for (String userName : userNames) {
        List<String> scopes = new ArrayList<>();
        if ("bob".equals(userName)) {
            scopes.add("Scope D");
        } else if ("alice".equals(userName)) {
            scopes.add("Scope C");
        } else if ("jdoe".equals(userName)) {
            scopes.add("Scope C");
            scopes.add("Scope D");
        }
        for (String scope : scopes) {
            PermissionTicketRepresentation ticket = new PermissionTicketRepresentation();
            ticket.setGranted(false);
            ticket.setOwner("test-user@localhost");
            ticket.setRequesterName(userName);
            ticket.setResource(resource.getId());
            ticket.setScopeName(scope);
            authzClient.protection("test-user@localhost", "password").permission().create(ticket);
        }
    }
    requests = doGet("/" + resource.getId() + "/permissions/requests", new TypeReference<List<Permission>>() {
    });
    assertEquals(3, requests.size());
    Iterator<Permission> iterator = requests.iterator();
    while (iterator.hasNext()) {
        Permission permission = iterator.next();
        String username = permission.getUsername();
        List<String> scopes = permission.getScopes();
        if ("bob".equals(username)) {
            scopes.clear();
        } else if ("jdoe".equals(username)) {
            scopes.remove("Scope C");
        }
    }
    SimpleHttp.doPut(getAccountUrl("resources/" + resource.getId() + "/permissions"), httpClient).auth(tokenUtil.getToken()).json(requests).asResponse();
    requests = doGet("/" + resource.getId() + "/permissions/requests", new TypeReference<List<Permission>>() {
    });
    assertTrue(requests.isEmpty());
    for (String user : Arrays.asList("alice", "jdoe")) {
        AbstractResourceService.ResourcePermission sharedResource = getSharedWithMe(user).stream().filter(resource1 -> resource1.getId().equals(resource.getId())).findAny().orElse(null);
        assertNotNull(sharedResource);
        Set<ScopeRepresentation> scopes = sharedResource.getScopes();
        if ("alice".equals(user)) {
            assertEquals(1, scopes.size());
            assertTrue(scopes.stream().anyMatch(scope -> "Scope C".equals(scope.getName())));
        } else if ("jdoe".equals(user)) {
            assertEquals(1, scopes.size());
            assertTrue(scopes.stream().anyMatch(scope -> "Scope D".equals(scope.getName())));
        }
    }
}
Also used : ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) Profile(org.keycloak.common.Profile) Resource(org.keycloak.services.resources.account.resources.AbstractResourceService.Resource) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) HashMap(java.util.HashMap) AuthzClient(org.keycloak.authorization.client.AuthzClient) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) Configuration(org.keycloak.authorization.client.Configuration) SimpleHttp(org.keycloak.broker.provider.util.SimpleHttp) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) AccessToken(org.keycloak.representations.AccessToken) UserBuilder(org.keycloak.testsuite.util.UserBuilder) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) TypeReference(com.fasterxml.jackson.core.type.TypeReference) LinkedList(java.util.LinkedList) ClientResource(org.keycloak.admin.client.resource.ClientResource) ProfileAssume(org.keycloak.testsuite.ProfileAssume) AbstractResourceService(org.keycloak.services.resources.account.resources.AbstractResourceService) TokenUtil(org.keycloak.testsuite.util.TokenUtil) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) JWSInput(org.keycloak.jose.jws.JWSInput) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Iterator(java.util.Iterator) Assert.assertNotNull(org.junit.Assert.assertNotNull) KeycloakUriBuilder(org.keycloak.common.util.KeycloakUriBuilder) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) JsonSerialization(org.keycloak.util.JsonSerialization) Consumer(java.util.function.Consumer) List(java.util.List) AccountRoles(org.keycloak.models.AccountRoles) Assert.assertNull(org.junit.Assert.assertNull) Response(javax.ws.rs.core.Response) Permission(org.keycloak.services.resources.account.resources.AbstractResourceService.Permission) ClientBuilder(org.keycloak.testsuite.util.ClientBuilder) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Resource(org.keycloak.services.resources.account.resources.AbstractResourceService.Resource) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) ClientResource(org.keycloak.admin.client.resource.ClientResource) ArrayList(java.util.ArrayList) AbstractResourceService(org.keycloak.services.resources.account.resources.AbstractResourceService) Permission(org.keycloak.services.resources.account.resources.AbstractResourceService.Permission) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Test(org.junit.Test)

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