Search in sources :

Example 31 with ScopePermissionRepresentation

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

the class EntitlementAPITest method testOverridePermission.

@Test
public void testOverridePermission() 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);
    }
    ResourcePermissionRepresentation typedResourcePermission = new ResourcePermissionRepresentation();
    typedResourcePermission.setName(KeycloakModelUtils.generateId());
    typedResourcePermission.setResourceType("resource");
    typedResourcePermission.addPolicy(onlyOwnerPolicy.getName());
    try (Response response = authorization.permissions().resource().create(typedResourcePermission)) {
        typedResourcePermission = response.readEntity(ResourcePermissionRepresentation.class);
    }
    ResourceRepresentation martaResource = new ResourceRepresentation();
    martaResource.setType("resource");
    martaResource.setName(KeycloakModelUtils.generateId());
    martaResource.addScope("read", "update");
    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"));
    }
    typedResourcePermission.setResourceType(null);
    typedResourcePermission.addResource(typedResource.getName());
    authorization.permissions().resource().findById(typedResourcePermission.getId()).update(typedResourcePermission);
    // now kolo can access marta's resources, last permission is overriding policies from typed 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("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) 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) 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)

Example 32 with ScopePermissionRepresentation

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

the class EntitlementAPITest method testDenyScopeNotManagedByScopePolicy.

@Test
public void testDenyScopeNotManagedByScopePolicy() 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.addResource(resource.getId());
    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");
    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(resource.getId(), grantedPermission.getResourceId());
        assertEquals(1, grantedPermission.getScopes().size());
        assertThat(grantedPermission.getScopes(), hasItem("sensors:view"));
    }
    request = new AuthorizationRequest();
    request.addPermission(resource.getId(), "sensors:update");
    this.expectedException.expect(AuthorizationDeniedException.class);
    this.expectedException.expectCause(Matchers.allOf(Matchers.instanceOf(HttpResponseException.class), Matchers.hasProperty("statusCode", Matchers.is(403))));
    this.expectedException.reportMissingExceptionWithMessage("should fail, session invalidated");
    authzClient.authorization().authorize(request);
}
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 33 with ScopePermissionRepresentation

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

the class EntitlementAPITest method testObtainAllEntitlementsForScope.

@Test
public void testObtainAllEntitlementsForScope() 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();
    Set<String> resourceIds = new HashSet<>();
    ResourceRepresentation resource = new ResourceRepresentation();
    resource.setName(KeycloakModelUtils.generateId());
    resource.addScope("sensors:view", "sensors:update", "sensors:delete");
    try (Response response = authorization.resources().create(resource)) {
        resourceIds.add(response.readEntity(ResourceRepresentation.class).getId());
    }
    resource = new ResourceRepresentation();
    resource.setName(KeycloakModelUtils.generateId());
    resource.addScope("sensors:view", "sensors:update");
    try (Response response = authorization.resources().create(resource)) {
        resourceIds.add(response.readEntity(ResourceRepresentation.class).getId());
    }
    ScopePermissionRepresentation permission = new ScopePermissionRepresentation();
    permission.setName(KeycloakModelUtils.generateId());
    permission.addScope("sensors:view", "sensors: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(null, "sensors:view");
    AuthorizationResponse response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    Collection<Permission> permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(2, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertTrue(resourceIds.containsAll(Arrays.asList(grantedPermission.getResourceId())));
        assertEquals(1, grantedPermission.getScopes().size());
        assertTrue(grantedPermission.getScopes().containsAll(Arrays.asList("sensors:view")));
    }
    request.addPermission(null, "sensors:view", "sensors:update");
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(2, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertTrue(resourceIds.containsAll(Arrays.asList(grantedPermission.getResourceId())));
        assertEquals(2, grantedPermission.getScopes().size());
        assertTrue(grantedPermission.getScopes().containsAll(Arrays.asList("sensors:view", "sensors:update")));
    }
    request.addPermission(null, "sensors:view", "sensors:update", "sensors:delete");
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(2, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertTrue(resourceIds.containsAll(Arrays.asList(grantedPermission.getResourceId())));
        assertEquals(2, grantedPermission.getScopes().size());
        assertTrue(grantedPermission.getScopes().containsAll(Arrays.asList("sensors:view", "sensors:update")));
    }
    request = new AuthorizationRequest();
    request.addPermission(null, "sensors:view");
    request.addPermission(null, "sensors:update");
    response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(2, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertTrue(resourceIds.containsAll(Arrays.asList(grantedPermission.getResourceId())));
        assertEquals(2, grantedPermission.getScopes().size());
        assertTrue(grantedPermission.getScopes().containsAll(Arrays.asList("sensors:view", "sensors: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) HashSet(java.util.HashSet) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Example 34 with ScopePermissionRepresentation

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

the class PolicyEnforcerTest method testMatchHttpVerbsToScopes.

@Test
public void testMatchHttpVerbsToScopes() {
    ClientResource clientResource = getClientResource(RESOURCE_SERVER_CLIENT_ID);
    ResourceRepresentation resource = createResource(clientResource, "Resource With HTTP Scopes", "/api/resource-with-scope");
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getName());
    permission.addPolicy("Always Grant Policy");
    PermissionsResource permissions = clientResource.authorization().permissions();
    permissions.resource().create(permission).close();
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-match-http-verbs-scopes.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    String token = response.getAccessToken();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/resource-with-scope", token);
    AuthorizationContext context = policyEnforcer.enforce(httpFacade);
    assertFalse("Should fail because resource does not have any scope named GET", context.isGranted());
    assertEquals(403, TestResponse.class.cast(httpFacade.getResponse()).getStatus());
    resource.addScope("GET", "POST");
    clientResource.authorization().resources().resource(resource.getId()).update(resource);
    deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-match-http-verbs-scopes.json"));
    policyEnforcer = deployment.getPolicyEnforcer();
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    // create a PATCH scope without associated it with the resource so that a PATCH request is denied accordingly even though
    // the scope exists on the server
    clientResource.authorization().scopes().create(new ScopeRepresentation("PATCH"));
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "PATCH");
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    ScopePermissionRepresentation postPermission = new ScopePermissionRepresentation();
    postPermission.setName("GET permission");
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Deny Policy");
    permissions.scope().create(postPermission).close();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Grant Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    AuthzClient authzClient = getAuthzClient("default-keycloak.json");
    AuthorizationResponse authorize = authzClient.authorization(token).authorize();
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Deny Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    authorize = authzClient.authorization(token).authorize();
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Grant Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    authorize = authzClient.authorization(token).authorize();
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("POST");
    postPermission.addPolicy("Always Deny Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(null, "GET");
    authorize = authzClient.authorization(token).authorize(request);
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) OIDCHttpFacade(org.keycloak.adapters.OIDCHttpFacade) AuthorizationContext(org.keycloak.AuthorizationContext) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionsResource(org.keycloak.admin.client.resource.PermissionsResource) AuthzClient(org.keycloak.authorization.client.AuthzClient) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) ClientResource(org.keycloak.admin.client.resource.ClientResource) PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 35 with ScopePermissionRepresentation

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

the class EntitlementAPITest method testPermissionsWithResourceAttributes.

@Test
public void testPermissionsWithResourceAttributes() throws Exception {
    ClientResource client = getClient(getRealm(), RESOURCE_SERVER_TEST);
    AuthorizationResource authorization = client.authorization();
    JSPolicyRepresentation onlyPublicResourcesPolicy = new JSPolicyRepresentation();
    onlyPublicResourcesPolicy.setName(KeycloakModelUtils.generateId());
    onlyPublicResourcesPolicy.setCode("var createPermission = $evaluation.getPermission();\n" + "var resource = createPermission.getResource();\n" + "\n" + "if (resource) {\n" + "    var attributes = resource.getAttributes();\n" + "    var visibility = attributes.get('visibility');\n" + "    \n" + "    if (visibility && \"private\".equals(visibility.get(0))) {\n" + "        $evaluation.deny();\n" + "      } else {\n" + "        $evaluation.grant();\n" + "    }\n" + "}");
    authorization.policies().js().create(onlyPublicResourcesPolicy).close();
    JSPolicyRepresentation onlyOwnerPolicy = createOnlyOwnerPolicy();
    authorization.policies().js().create(onlyOwnerPolicy).close();
    ResourceRepresentation typedResource = new ResourceRepresentation();
    typedResource.setType("resource");
    typedResource.setName(KeycloakModelUtils.generateId());
    try (Response response = authorization.resources().create(typedResource)) {
        typedResource = response.readEntity(ResourceRepresentation.class);
    }
    ResourceRepresentation userResource = new ResourceRepresentation();
    userResource.setName(KeycloakModelUtils.generateId());
    userResource.setType("resource");
    userResource.setOwner("marta");
    Map<String, List<String>> attributes = new HashMap<>();
    attributes.put("visibility", Arrays.asList("private"));
    userResource.setAttributes(attributes);
    try (Response response = authorization.resources().create(userResource)) {
        userResource = response.readEntity(ResourceRepresentation.class);
    }
    ResourcePermissionRepresentation typedResourcePermission = new ResourcePermissionRepresentation();
    typedResourcePermission.setName(KeycloakModelUtils.generateId());
    typedResourcePermission.setResourceType("resource");
    typedResourcePermission.addPolicy(onlyPublicResourcesPolicy.getName());
    try (Response response = authorization.permissions().resource().create(typedResourcePermission)) {
        typedResourcePermission = response.readEntity(ResourcePermissionRepresentation.class);
    }
    // marta can access any public resource
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(typedResource.getId());
    request.addPermission(userResource.getId());
    AuthorizationResponse response = authzClient.authorization("marta", "password").authorize(request);
    assertNotNull(response.getToken());
    Collection<Permission> permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertEquals(typedResource.getName(), grantedPermission.getResourceName());
    }
    typedResourcePermission.addPolicy(onlyOwnerPolicy.getName());
    typedResourcePermission.setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
    authorization.permissions().resource().findById(typedResourcePermission.getId()).update(typedResourcePermission);
    response = authzClient.authorization("marta", "password").authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(2, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertThat(Arrays.asList(typedResource.getName(), userResource.getName()), Matchers.hasItem(grantedPermission.getResourceName()));
    }
    typedResource.setAttributes(attributes);
    authorization.resources().resource(typedResource.getId()).update(typedResource);
    response = authzClient.authorization("marta", "password").authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertThat(userResource.getName(), Matchers.equalTo(grantedPermission.getResourceName()));
    }
    userResource.addScope("create", "read");
    authorization.resources().resource(userResource.getId()).update(userResource);
    typedResource.addScope("create", "read");
    authorization.resources().resource(typedResource.getId()).update(typedResource);
    ScopePermissionRepresentation createPermission = new ScopePermissionRepresentation();
    createPermission.setName(KeycloakModelUtils.generateId());
    createPermission.addScope("create");
    createPermission.addPolicy(onlyPublicResourcesPolicy.getName());
    authorization.permissions().scope().create(createPermission).close();
    response = authzClient.authorization("marta", "password").authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertThat(userResource.getName(), Matchers.equalTo(grantedPermission.getResourceName()));
        assertThat(grantedPermission.getScopes(), Matchers.not(Matchers.hasItem("create")));
    }
    typedResource.setAttributes(new HashMap<>());
    authorization.resources().resource(typedResource.getId()).update(typedResource);
    response = authzClient.authorization("marta", "password").authorize();
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    for (Permission grantedPermission : permissions) {
        if (grantedPermission.getResourceName().equals(userResource.getName())) {
            assertThat(grantedPermission.getScopes(), Matchers.not(Matchers.hasItem("create")));
        } else if (grantedPermission.getResourceName().equals(typedResource.getName())) {
            assertThat(grantedPermission.getScopes(), Matchers.containsInAnyOrder("create", "read"));
        }
    }
    request = new AuthorizationRequest();
    request.addPermission(typedResource.getId());
    request.addPermission(userResource.getId());
    response = authzClient.authorization("marta", "password").authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    for (Permission grantedPermission : permissions) {
        if (grantedPermission.getResourceName().equals(userResource.getName())) {
            assertThat(grantedPermission.getScopes(), Matchers.not(Matchers.hasItem("create")));
        } else if (grantedPermission.getResourceName().equals(typedResource.getName())) {
            assertThat(grantedPermission.getScopes(), Matchers.containsInAnyOrder("create", "read"));
        }
    }
    request = new AuthorizationRequest();
    request.addPermission(userResource.getId());
    request.addPermission(typedResource.getId());
    response = authzClient.authorization("marta", "password").authorize(request);
    assertNotNull(response.getToken());
    permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    for (Permission grantedPermission : permissions) {
        if (grantedPermission.getResourceName().equals(userResource.getName())) {
            assertThat(grantedPermission.getScopes(), Matchers.not(Matchers.hasItem("create")));
        } else if (grantedPermission.getResourceName().equals(typedResource.getName())) {
            assertThat(grantedPermission.getScopes(), Matchers.containsInAnyOrder("create", "read"));
        }
    }
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) HashMap(java.util.HashMap) 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) AuthzClient(org.keycloak.authorization.client.AuthzClient) Permission(org.keycloak.representations.idm.authorization.Permission) ClientResource(org.keycloak.admin.client.resource.ClientResource) List(java.util.List) ArrayList(java.util.ArrayList) 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