Search in sources :

Example 6 with ScopePermissionRepresentation

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

the class EntitlementAPITest method testObtainAllEntitlementsInvalidScope.

@Test
public void testObtainAllEntitlementsInvalidScope() 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(KeycloakModelUtils.generateId());
    resource.addScope("sensors:view", "sensors:update", "sensors:delete");
    try (Response response = authorization.resources().create(resource)) {
        resource = response.readEntity(ResourceRepresentation.class);
    }
    ScopePermissionRepresentation permission = new ScopePermissionRepresentation();
    permission.setName(KeycloakModelUtils.generateId());
    permission.addScope("sensors:view");
    permission.addPolicy(policy.getName());
    authorization.permissions().scope().create(permission).close();
    String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "kolo", "password").getAccessToken();
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(resource.getId(), "sensors:view_invalid");
    try {
        authzClient.authorization(accessToken).authorize(request);
        fail("scope is invalid");
    } catch (RuntimeException expected) {
        assertEquals(400, HttpResponseException.class.cast(expected.getCause()).getStatusCode());
        assertTrue(HttpResponseException.class.cast(expected.getCause()).toString().contains("invalid_scope"));
    }
    request = new AuthorizationRequest();
    request.addPermission(null, "sensors:view_invalid");
    try {
        authzClient.authorization(accessToken).authorize(request);
        fail("scope is invalid");
    } catch (RuntimeException expected) {
        assertEquals(400, HttpResponseException.class.cast(expected.getCause()).getStatusCode());
        assertTrue(HttpResponseException.class.cast(expected.getCause()).toString().contains("invalid_scope"));
    }
}
Also used : 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) AuthzClient(org.keycloak.authorization.client.AuthzClient) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Example 7 with ScopePermissionRepresentation

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

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

the class EntitlementAPITest method testObtainAllEntitlementsInvalidResource.

@Test
public void testObtainAllEntitlementsInvalidResource() 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("Sensors");
    resource.addScope("sensors:view", "sensors:update", "sensors:delete");
    authorization.resources().create(resource).close();
    ScopePermissionRepresentation permission = new ScopePermissionRepresentation();
    permission.setName("View Sensor");
    permission.addScope("sensors:view");
    permission.addPolicy(policy.getName());
    authorization.permissions().scope().create(permission).close();
    String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "kolo", "password").getAccessToken();
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission("Sensortest", "sensors:view");
    getTestContext().getTestingClient().testing().clearEventQueue();
    try {
        authzClient.authorization(accessToken).authorize(request);
        fail("resource is invalid");
    } catch (RuntimeException expected) {
        assertEquals(400, HttpResponseException.class.cast(expected.getCause()).getStatusCode());
        assertTrue(HttpResponseException.class.cast(expected.getCause()).toString().contains("invalid_resource"));
    }
    events.expect(EventType.PERMISSION_TOKEN_ERROR).realm(getRealm().toRepresentation().getId()).client(RESOURCE_SERVER_TEST).session((String) null).error("invalid_request").detail("reason", "Resource with id [Sensortest] does not exist.").user(isUUID()).assertEvent();
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Example 9 with ScopePermissionRepresentation

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

the class EntitlementAPITest method testObtainAllEntitlementsForResourceWithScopePermission.

@Test
public void testObtainAllEntitlementsForResourceWithScopePermission() 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 resourceWithoutType = new ResourceRepresentation();
    resourceWithoutType.setName(KeycloakModelUtils.generateId());
    resourceWithoutType.addScope("scope:view", "scope:update", "scope:delete");
    try (Response response = authorization.resources().create(resourceWithoutType)) {
        resourceWithoutType = response.readEntity(ResourceRepresentation.class);
    }
    ResourceRepresentation resourceWithType = new ResourceRepresentation();
    resourceWithType.setName(KeycloakModelUtils.generateId());
    resourceWithType.setType("type-one");
    resourceWithType.addScope("scope:view", "scope:update", "scope:delete");
    try (Response response = authorization.resources().create(resourceWithType)) {
        resourceWithType = response.readEntity(ResourceRepresentation.class);
    }
    ScopePermissionRepresentation permission = new ScopePermissionRepresentation();
    permission.setName(KeycloakModelUtils.generateId());
    permission.addResource(resourceWithoutType.getId());
    permission.addScope("scope:view");
    permission.addPolicy(policy.getName());
    authorization.permissions().scope().create(permission).close();
    permission = new ScopePermissionRepresentation();
    permission.setName(KeycloakModelUtils.generateId());
    permission.setResourceType("type-one");
    permission.addScope("scope:update");
    permission.addPolicy(policy.getName());
    authorization.permissions().scope().create(permission).close();
    String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "kolo", "password").getAccessToken();
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(resourceWithoutType.getId(), "scope:view", "scope:update", "scope:delete");
    AuthorizationResponse response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    Collection<Permission> permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(resourceWithoutType.getId(), grantedPermission.getResourceId());
        assertEquals(1, grantedPermission.getScopes().size());
        assertTrue(grantedPermission.getScopes().containsAll(Arrays.asList("scope:view")));
    }
    request = new AuthorizationRequest();
    request.addPermission(resourceWithType.getId(), "scope:view", "scope:update", "scope:delete");
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(resourceWithType.getId(), grantedPermission.getResourceId());
        assertEquals(1, grantedPermission.getScopes().size());
        assertTrue(grantedPermission.getScopes().containsAll(Arrays.asList("scope:update")));
    }
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) 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) AuthzClient(org.keycloak.authorization.client.AuthzClient) Permission(org.keycloak.representations.idm.authorization.Permission) ClientResource(org.keycloak.admin.client.resource.ClientResource) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Example 10 with ScopePermissionRepresentation

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

the class EntitlementAPITest method testOverrideParentScopePermission.

@Test
public void testOverrideParentScopePermission() throws Exception {
    ClientResource client = getClient(getRealm(), RESOURCE_SERVER_TEST);
    AuthorizationResource authorization = client.authorization();
    JSPolicyRepresentation onlyOwnerPolicy = createOnlyOwnerPolicy();
    authorization.policies().js().create(onlyOwnerPolicy).close();
    ResourceRepresentation typedResource = new ResourceRepresentation();
    typedResource.setType("resource");
    typedResource.setName(KeycloakModelUtils.generateId());
    typedResource.addScope("read", "update");
    try (Response response = authorization.resources().create(typedResource)) {
        typedResource = response.readEntity(ResourceRepresentation.class);
    }
    ScopePermissionRepresentation typedResourcePermission = new ScopePermissionRepresentation();
    typedResourcePermission.setName(KeycloakModelUtils.generateId());
    typedResourcePermission.addResource(typedResource.getName());
    typedResourcePermission.addPolicy(onlyOwnerPolicy.getName());
    typedResourcePermission.addScope("read", "update");
    authorization.permissions().scope().create(typedResourcePermission).close();
    ResourceRepresentation martaResource = new ResourceRepresentation();
    martaResource.setType("resource");
    martaResource.setName(KeycloakModelUtils.generateId());
    martaResource.addScope("read");
    martaResource.setOwner("marta");
    try (Response response = authorization.resources().create(martaResource)) {
        martaResource = response.readEntity(ResourceRepresentation.class);
    }
    String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "marta", "password").getAccessToken();
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(martaResource.getName());
    // marta can access her resource
    AuthorizationResponse response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    Collection<Permission> permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(martaResource.getName(), grantedPermission.getResourceName());
        Set<String> scopes = grantedPermission.getScopes();
        assertEquals(2, scopes.size());
        assertThat(scopes, Matchers.containsInAnyOrder("read", "update"));
    }
    accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "kolo", "password").getAccessToken();
    authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    request = new AuthorizationRequest();
    request.addPermission(martaResource.getId());
    try {
        authzClient.authorization(accessToken).authorize(request);
        fail("kolo can not access marta resource");
    } catch (RuntimeException expected) {
        assertEquals(403, HttpResponseException.class.cast(expected.getCause()).getStatusCode());
        assertTrue(HttpResponseException.class.cast(expected.getCause()).toString().contains("access_denied"));
    }
    UserPolicyRepresentation onlyKoloPolicy = new UserPolicyRepresentation();
    onlyKoloPolicy.setName(KeycloakModelUtils.generateId());
    onlyKoloPolicy.addUser("kolo");
    authorization.policies().user().create(onlyKoloPolicy).close();
    ResourcePermissionRepresentation martaResourcePermission = new ResourcePermissionRepresentation();
    martaResourcePermission.setName(KeycloakModelUtils.generateId());
    martaResourcePermission.addResource(martaResource.getId());
    martaResourcePermission.addPolicy(onlyKoloPolicy.getName());
    try (Response response1 = authorization.permissions().resource().create(martaResourcePermission)) {
        martaResourcePermission = response1.readEntity(ResourcePermissionRepresentation.class);
    }
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(martaResource.getName(), grantedPermission.getResourceName());
        Set<String> scopes = grantedPermission.getScopes();
        assertEquals(2, scopes.size());
        assertThat(scopes, Matchers.containsInAnyOrder("read", "update"));
    }
    ScopePermissionRepresentation martaResourceUpdatePermission = new ScopePermissionRepresentation();
    martaResourceUpdatePermission.setName(KeycloakModelUtils.generateId());
    martaResourceUpdatePermission.addResource(martaResource.getId());
    martaResourceUpdatePermission.addScope("update");
    martaResourceUpdatePermission.addPolicy(onlyOwnerPolicy.getName());
    try (Response response1 = authorization.permissions().scope().create(martaResourceUpdatePermission)) {
        martaResourceUpdatePermission = response1.readEntity(ScopePermissionRepresentation.class);
    }
    // now kolo can only read, but not update
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(martaResource.getName(), grantedPermission.getResourceName());
        Set<String> scopes = grantedPermission.getScopes();
        assertEquals(1, scopes.size());
        assertThat(scopes, Matchers.containsInAnyOrder("read"));
    }
    authorization.permissions().resource().findById(martaResourcePermission.getId()).remove();
    try {
        // after removing permission to marta resource, kolo can not access any scope in the resource
        authzClient.authorization(accessToken).authorize(request);
        fail("kolo can not access marta resource");
    } catch (RuntimeException expected) {
        assertEquals(403, HttpResponseException.class.cast(expected.getCause()).getStatusCode());
        assertTrue(HttpResponseException.class.cast(expected.getCause()).toString().contains("access_denied"));
    }
    martaResourceUpdatePermission.addPolicy(onlyKoloPolicy.getName());
    martaResourceUpdatePermission.setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
    authorization.permissions().scope().findById(martaResourceUpdatePermission.getId()).update(martaResourceUpdatePermission);
    // now kolo can access because update permission changed to allow him to access the resource using an affirmative strategy
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(martaResource.getName(), grantedPermission.getResourceName());
        Set<String> scopes = grantedPermission.getScopes();
        assertEquals(1, scopes.size());
        assertThat(scopes, Matchers.containsInAnyOrder("update"));
    }
    accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "marta", "password").getAccessToken();
    // marta can still access her resource
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(martaResource.getName(), grantedPermission.getResourceName());
        Set<String> scopes = grantedPermission.getScopes();
        assertEquals(2, scopes.size());
        assertThat(scopes, Matchers.containsInAnyOrder("update", "read"));
    }
    authorization.permissions().scope().findById(martaResourceUpdatePermission.getId()).remove();
    accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "kolo", "password").getAccessToken();
    try {
        // back to original setup, permissions not granted by the type resource
        authzClient.authorization(accessToken).authorize(request);
        fail("kolo can not access marta resource");
    } catch (RuntimeException expected) {
        assertEquals(403, HttpResponseException.class.cast(expected.getCause()).getStatusCode());
        assertTrue(HttpResponseException.class.cast(expected.getCause()).toString().contains("access_denied"));
    }
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) 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) AuthzClient(org.keycloak.authorization.client.AuthzClient) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) Permission(org.keycloak.representations.idm.authorization.Permission) ClientResource(org.keycloak.admin.client.resource.ClientResource) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Aggregations

ScopePermissionRepresentation (org.keycloak.representations.idm.authorization.ScopePermissionRepresentation)43 Test (org.junit.Test)32 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)23 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)17 AuthzClient (org.keycloak.authorization.client.AuthzClient)16 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)16 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)16 ClientResource (org.keycloak.admin.client.resource.ClientResource)15 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)15 Permission (org.keycloak.representations.idm.authorization.Permission)14 Response (javax.ws.rs.core.Response)13 OAuthClient (org.keycloak.testsuite.util.OAuthClient)13 PermissionResponse (org.keycloak.representations.idm.authorization.PermissionResponse)11 TokenIntrospectionResponse (org.keycloak.authorization.client.representation.TokenIntrospectionResponse)10 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)10 HttpResponseException (org.keycloak.authorization.client.util.HttpResponseException)7 ResourcePermissionRepresentation (org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation)7 ScopePermissionsResource (org.keycloak.admin.client.resource.ScopePermissionsResource)6 ScopePermission (org.keycloak.testsuite.console.page.clients.authorization.permission.ScopePermission)5 ArrayList (java.util.ArrayList)4