Search in sources :

Example 11 with ScopeRepresentation

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

the class ResourceSetService method getScopes.

@Path("{id}/scopes")
@GET
@NoCache
@Produces("application/json")
public Response getScopes(@PathParam("id") String id) {
    requireView();
    StoreFactory storeFactory = authorization.getStoreFactory();
    Resource model = storeFactory.getResourceStore().findById(id, resourceServer.getId());
    if (model == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    List<ScopeRepresentation> scopes = model.getScopes().stream().map(scope -> {
        ScopeRepresentation representation = new ScopeRepresentation();
        representation.setId(scope.getId());
        representation.setName(scope.getName());
        return representation;
    }).collect(Collectors.toList());
    if (model.getType() != null && !model.getOwner().equals(resourceServer.getId())) {
        ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
        for (Resource typed : resourceStore.findByType(model.getType(), resourceServer.getId())) {
            if (typed.getOwner().equals(resourceServer.getId()) && !typed.getId().equals(model.getId())) {
                scopes.addAll(typed.getScopes().stream().map(model1 -> {
                    ScopeRepresentation scope = new ScopeRepresentation();
                    scope.setId(model1.getId());
                    scope.setName(model1.getName());
                    String iconUri = model1.getIconUri();
                    if (iconUri != null) {
                        scope.setIconUri(iconUri);
                    }
                    return scope;
                }).filter(scopeRepresentation -> !scopes.contains(scopeRepresentation)).collect(Collectors.toList()));
            }
        }
    }
    return Response.ok(scopes).build();
}
Also used : 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) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ResourceStore(org.keycloak.authorization.store.ResourceStore) 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 12 with ScopeRepresentation

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

the class EntitlementAPITest method testPermissionOrder.

@Test
public void testPermissionOrder() throws Exception {
    ClientResource client = getClient(getRealm(), RESOURCE_SERVER_TEST);
    AuthorizationResource authorization = client.authorization();
    JSPolicyRepresentation policy = new JSPolicyRepresentation();
    policy.setName(KeycloakModelUtils.generateId());
    policy.setCode("$evaluation.grant();");
    authorization.policies().js().create(policy).close();
    ResourceRepresentation resource = new ResourceRepresentation();
    resource.setName("my_resource");
    resource.addScope("entity:read");
    try (Response response = authorization.resources().create(resource)) {
        resource = response.readEntity(ResourceRepresentation.class);
    }
    ScopeRepresentation featureAccessScope = new ScopeRepresentation("feature:access");
    authorization.scopes().create(featureAccessScope);
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    permission.setName(KeycloakModelUtils.generateId());
    permission.addPolicy(policy.getName());
    permission.addResource(resource.getId());
    authorization.permissions().resource().create(permission).close();
    ScopePermissionRepresentation scopePermission = new ScopePermissionRepresentation();
    scopePermission.setName(KeycloakModelUtils.generateId());
    scopePermission.addPolicy(policy.getName());
    scopePermission.addScope(featureAccessScope.getName());
    authorization.permissions().scope().create(scopePermission).close();
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(null, "entity:read");
    request.addPermission(null, "feature:access");
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationResponse response = authzClient.authorization().authorize(request);
    AccessToken token = toAccessToken(response.getToken());
    Authorization result = token.getAuthorization();
    assertEquals(2, result.getPermissions().size());
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() == null && p.getScopes().contains(featureAccessScope.getName())));
    String resourceId = resource.getId();
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() != null && p.getResourceId().equals(resourceId) && p.getScopes().contains("entity:read")));
    request = new AuthorizationRequest();
    request.addPermission(null, "feature:access");
    request.addPermission(null, "entity:read");
    response = authzClient.authorization().authorize(request);
    token = toAccessToken(response.getToken());
    result = token.getAuthorization();
    assertEquals(2, result.getPermissions().size());
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() == null && p.getScopes().contains(featureAccessScope.getName())));
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() != null && p.getResourceId().equals(resourceId) && p.getScopes().contains("entity:read")));
}
Also used : RealmEventsConfigRepresentation(org.keycloak.representations.idm.RealmEventsConfigRepresentation) TestApplicationResourceUrls(org.keycloak.testsuite.client.resources.TestApplicationResourceUrls) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Arrays(java.util.Arrays) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AssertEvents(org.keycloak.testsuite.AssertEvents) AuthzClient(org.keycloak.authorization.client.AuthzClient) Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Assert.assertThat(org.junit.Assert.assertThat) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Configuration(org.keycloak.authorization.client.Configuration) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) AccessToken(org.keycloak.representations.AccessToken) Map(java.util.Map) After(org.junit.After) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) Assert.fail(org.junit.Assert.fail) ClientResource(org.keycloak.admin.client.resource.ClientResource) RealmResource(org.keycloak.admin.client.resource.RealmResource) Collection(java.util.Collection) RolesBuilder(org.keycloak.testsuite.util.RolesBuilder) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) RoleBuilder(org.keycloak.testsuite.util.RoleBuilder) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) List(java.util.List) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) Response(javax.ws.rs.core.Response) Assert.assertFalse(org.junit.Assert.assertFalse) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) NotNull(org.jetbrains.annotations.NotNull) HttpClients(org.apache.http.impl.client.HttpClients) OAuth2Constants(org.keycloak.OAuth2Constants) HardcodedClaim(org.keycloak.protocol.oidc.mappers.HardcodedClaim) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Permission(org.keycloak.representations.idm.authorization.Permission) ResourceResource(org.keycloak.admin.client.resource.ResourceResource) HashMap(java.util.HashMap) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ScopePermissionsResource(org.keycloak.admin.client.resource.ScopePermissionsResource) RealmBuilder(org.keycloak.testsuite.util.RealmBuilder) HttpClient(org.apache.http.client.HttpClient) AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) UserBuilder(org.keycloak.testsuite.util.UserBuilder) TokenIntrospectionResponse(org.keycloak.authorization.client.representation.TokenIntrospectionResponse) ArquillianResource(org.jboss.arquillian.test.api.ArquillianResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthServer(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer) ContainerController(org.jboss.arquillian.container.test.api.ContainerController) ExpectedException(org.junit.rules.ExpectedException) Base64Url(org.keycloak.common.util.Base64Url) Before(org.junit.Before) ApiUtil(org.keycloak.testsuite.admin.ApiUtil) OIDCAttributeMapperHelper(org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper) Authorization(org.keycloak.representations.AccessToken.Authorization) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Matchers(org.hamcrest.Matchers) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) IOException(java.io.IOException) Test(org.junit.Test) EventType(org.keycloak.events.EventType) DecisionStrategy(org.keycloak.representations.idm.authorization.DecisionStrategy) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) JsonSerialization(org.keycloak.util.JsonSerialization) Assert.assertNull(org.junit.Assert.assertNull) AssertEvents.isUUID(org.keycloak.testsuite.AssertEvents.isUUID) Rule(org.junit.Rule) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) ClientBuilder(org.keycloak.testsuite.util.ClientBuilder) Assert.assertEquals(org.junit.Assert.assertEquals) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) TokenIntrospectionResponse(org.keycloak.authorization.client.representation.TokenIntrospectionResponse) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) Authorization(org.keycloak.representations.AccessToken.Authorization) AuthzClient(org.keycloak.authorization.client.AuthzClient) AccessToken(org.keycloak.representations.AccessToken) ClientResource(org.keycloak.admin.client.resource.ClientResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Example 13 with ScopeRepresentation

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

the class PermissionManagementTest method testRemoveScopeFromResource.

@Test
public void testRemoveScopeFromResource() throws Exception {
    ResourceRepresentation resource = addResource("Resource A", "kolo", true, "ScopeA", "ScopeB");
    PermissionRequest permissionRequest = new PermissionRequest(resource.getId(), "ScopeA", "ScopeB");
    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) {
    }
    AuthorizationResource authorization = getClient(getRealm()).authorization();
    ResourceScopesResource scopes = authorization.scopes();
    ScopeRepresentation removedScope = scopes.findByName("ScopeA");
    List permissions = authzClient.protection().permission().findByScope(removedScope.getId());
    assertFalse(permissions.isEmpty());
    resource.setScopes(new HashSet<>());
    resource.addScope("ScopeB");
    authorization.resources().resource(resource.getId()).update(resource);
    permissions = authzClient.protection().permission().findByScope(removedScope.getId());
    assertTrue(permissions.isEmpty());
    ScopeRepresentation scopeB = scopes.findByName("ScopeB");
    permissions = authzClient.protection().permission().findByScope(scopeB.getId());
    assertFalse(permissions.isEmpty());
}
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 14 with ScopeRepresentation

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

the class ConflictingScopePermissionTest method createResourcesAndScopes.

private void createResourcesAndScopes() throws IOException {
    AuthzClient authzClient = getAuthzClient();
    Set<ScopeRepresentation> scopes = new HashSet<>();
    scopes.add(new ScopeRepresentation("read"));
    scopes.add(new ScopeRepresentation("write"));
    scopes.add(new ScopeRepresentation("execute"));
    List<ResourceRepresentation> resources = new ArrayList<>();
    resources.add(new ResourceRepresentation("Resource A", scopes));
    resources.add(new ResourceRepresentation("Resource B", scopes));
    resources.add(new ResourceRepresentation("Resource C", scopes));
    resources.forEach(resource -> authzClient.protection().resource().create(resource));
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) ArrayList(java.util.ArrayList) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) HashSet(java.util.HashSet) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Example 15 with ScopeRepresentation

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

the class ScopePermissionManagementTest method configureTest.

@Before
public void configureTest() {
    super.configureTest();
    RolesResource realmRoles = testRealmResource().roles();
    realmRoles.create(new RoleRepresentation("Role A", "", false));
    realmRoles.create(new RoleRepresentation("Role B", "", false));
    RolePolicyRepresentation policyA = new RolePolicyRepresentation();
    policyA.setName("Policy A");
    policyA.addRole("Role A");
    AuthorizationResource authorization = testRealmResource().clients().get(newClient.getId()).authorization();
    PoliciesResource policies = authorization.policies();
    RolePoliciesResource roles = policies.role();
    roles.create(policyA);
    RolePolicyRepresentation policyB = new RolePolicyRepresentation();
    policyB.setName("Policy B");
    policyB.addRole("Role B");
    roles.create(policyB);
    UserPolicyRepresentation policyC = new UserPolicyRepresentation();
    policyC.setName("Policy C");
    policyC.addUser("test");
    policies.user().create(policyC).close();
    authorization.scopes().create(new ScopeRepresentation("Scope A"));
    authorization.scopes().create(new ScopeRepresentation("Scope B"));
    authorization.scopes().create(new ScopeRepresentation("Scope C"));
    ResourcesResource resources = authorization.resources();
    resources.create(new ResourceRepresentation("Resource A", "Scope A"));
    resources.create(new ResourceRepresentation("Resource B", "Scope B", "Scope C"));
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RolePolicyRepresentation(org.keycloak.representations.idm.authorization.RolePolicyRepresentation) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) RolePoliciesResource(org.keycloak.admin.client.resource.RolePoliciesResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) PoliciesResource(org.keycloak.admin.client.resource.PoliciesResource) RolePoliciesResource(org.keycloak.admin.client.resource.RolePoliciesResource) RolesResource(org.keycloak.admin.client.resource.RolesResource) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourcesResource(org.keycloak.admin.client.resource.ResourcesResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Before(org.junit.Before)

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