Search in sources :

Example 1 with PolicyRepresentation

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

the class ClientPolicyProviderFactory method onExport.

@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorization) {
    ClientPolicyRepresentation userRep = toRepresentation(policy, authorization);
    Map<String, String> config = new HashMap<>();
    try {
        RealmModel realm = authorization.getRealm();
        config.put("clients", JsonSerialization.writeValueAsString(userRep.getClients().stream().map(id -> realm.getClientById(id).getClientId()).collect(Collectors.toList())));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to export user policy [" + policy.getName() + "]", cause);
    }
    representation.setConfig(config);
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) Arrays(java.util.Arrays) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) Config(org.keycloak.Config) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Map(java.util.Map) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ResourceServer(org.keycloak.authorization.model.ResourceServer) PolicyProviderFactory(org.keycloak.authorization.policy.provider.PolicyProviderFactory) RealmModel(org.keycloak.models.RealmModel) Set(java.util.Set) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) PolicyStore(org.keycloak.authorization.store.PolicyStore) ClientRemovedEvent(org.keycloak.models.ClientModel.ClientRemovedEvent) Collectors(java.util.stream.Collectors) JsonSerialization(org.keycloak.util.JsonSerialization) Policy(org.keycloak.authorization.model.Policy) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) List(java.util.List) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) PolicyProvider(org.keycloak.authorization.policy.provider.PolicyProvider) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) HashMap(java.util.HashMap) IOException(java.io.IOException)

Example 2 with PolicyRepresentation

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

the class Helper method createRolePolicy.

public static Policy createRolePolicy(AuthorizationProvider authz, ResourceServer resourceServer, RoleModel role, String policyName) {
    PolicyRepresentation representation = new PolicyRepresentation();
    representation.setName(policyName);
    representation.setType("role");
    representation.setDecisionStrategy(DecisionStrategy.UNANIMOUS);
    representation.setLogic(Logic.POSITIVE);
    String roleValues = "[{\"id\":\"" + role.getId() + "\",\"required\": true}]";
    Map<String, String> config = new HashMap<>();
    config.put("roles", roleValues);
    representation.setConfig(config);
    return authz.getStoreFactory().getPolicyStore().create(representation, resourceServer);
}
Also used : PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) HashMap(java.util.HashMap)

Example 3 with PolicyRepresentation

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

the class DefaultAuthzConfigAdapterTest method testDefaultAuthzConfig.

@Test
public void testDefaultAuthzConfig() throws Exception {
    try {
        configureAuthorizationServices();
        this.deployer.deploy(RESOURCE_SERVER_ID);
        login();
        assertTrue(this.driver.getPageSource().contains("Your permissions are"));
        assertTrue(this.driver.getPageSource().contains("Default Resource"));
        boolean hasDefaultPermission = false;
        boolean hasDefaultPolicy = false;
        for (PolicyRepresentation policy : getAuthorizationResource().policies().policies()) {
            if ("Default Policy".equals(policy.getName())) {
                hasDefaultPolicy = true;
            }
            if ("Default Permission".equals(policy.getName())) {
                hasDefaultPermission = true;
            }
        }
        assertTrue(hasDefaultPermission);
        assertTrue(hasDefaultPolicy);
    } finally {
        this.deployer.undeploy(RESOURCE_SERVER_ID);
    }
}
Also used : PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) Test(org.junit.Test) AbstractExampleAdapterTest(org.keycloak.testsuite.adapter.AbstractExampleAdapterTest)

Example 4 with PolicyRepresentation

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

the class ExportUtils method createPolicyRepresentation.

private static PolicyRepresentation createPolicyRepresentation(AuthorizationProvider authorizationProvider, Policy policy) {
    try {
        PolicyRepresentation rep = toRepresentation(policy, authorizationProvider, true, true);
        Map<String, String> config = new HashMap<>(rep.getConfig());
        rep.setConfig(config);
        Set<Scope> scopes = policy.getScopes();
        if (!scopes.isEmpty()) {
            List<String> scopeNames = scopes.stream().map(Scope::getName).collect(Collectors.toList());
            config.put("scopes", JsonSerialization.writeValueAsString(scopeNames));
        }
        Set<Resource> policyResources = policy.getResources();
        if (!policyResources.isEmpty()) {
            List<String> resourceNames = policyResources.stream().map(Resource::getName).collect(Collectors.toList());
            config.put("resources", JsonSerialization.writeValueAsString(resourceNames));
        }
        Set<Policy> associatedPolicies = policy.getAssociatedPolicies();
        if (!associatedPolicies.isEmpty()) {
            config.put("applyPolicies", JsonSerialization.writeValueAsString(associatedPolicies.stream().map(associated -> associated.getName()).collect(Collectors.toList())));
        }
        return rep;
    } catch (Exception e) {
        throw new RuntimeException("Error while exporting policy [" + policy.getName() + "].", e);
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Version(org.keycloak.common.Version) RoleContainerModel(org.keycloak.models.RoleContainerModel) Map(java.util.Map) ModelToRepresentation.toRepresentation(org.keycloak.models.utils.ModelToRepresentation.toRepresentation) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) UserConsentRepresentation(org.keycloak.representations.idm.UserConsentRepresentation) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Collection(java.util.Collection) AuthorizationProviderFactory(org.keycloak.authorization.AuthorizationProviderFactory) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) PolicyStore(org.keycloak.authorization.store.PolicyStore) Collectors(java.util.stream.Collectors) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) List(java.util.List) Stream(java.util.stream.Stream) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) Profile(org.keycloak.common.Profile) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ScopeMappingRepresentation(org.keycloak.representations.idm.ScopeMappingRepresentation) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) LinkedList(java.util.LinkedList) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ResourceServer(org.keycloak.authorization.model.ResourceServer) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) OutputStream(java.io.OutputStream) RolesRepresentation(org.keycloak.representations.idm.RolesRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) CredentialModel(org.keycloak.credential.CredentialModel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) JsonSerialization(org.keycloak.util.JsonSerialization) Policy(org.keycloak.authorization.model.Policy) JsonFactory(com.fasterxml.jackson.core.JsonFactory) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) Resource(org.keycloak.authorization.model.Resource) HashMap(java.util.HashMap) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) Resource(org.keycloak.authorization.model.Resource) IOException(java.io.IOException) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) Scope(org.keycloak.authorization.model.Scope)

Example 5 with PolicyRepresentation

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

the class UsersTest method setupTestEnvironmentWithPermissions.

private RealmResource setupTestEnvironmentWithPermissions(boolean grp1ViewPermissions) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    String testUserId = createUser(realmId, "test-user", "password", "", "", "");
    // assign 'query-users' role to test user
    ClientRepresentation clientRepresentation = realm.clients().findByClientId("realm-management").get(0);
    String realmManagementId = clientRepresentation.getId();
    RoleRepresentation roleRepresentation = realm.clients().get(realmManagementId).roles().get("query-users").toRepresentation();
    realm.users().get(testUserId).roles().clientLevel(realmManagementId).add(Collections.singletonList(roleRepresentation));
    // create test users and groups
    List<GroupRepresentation> groups = setupUsersInGroupsWithPermissions();
    if (grp1ViewPermissions) {
        AuthorizationResource authorizationResource = realm.clients().get(realmManagementId).authorization();
        // create a user policy for the test user
        UserPolicyRepresentation policy = new UserPolicyRepresentation();
        String policyName = "test-policy";
        policy.setName(policyName);
        policy.setUsers(Collections.singleton(testUserId));
        authorizationResource.policies().user().create(policy).close();
        PolicyRepresentation policyRepresentation = authorizationResource.policies().findByName(policyName);
        // add the policy to grp1
        Optional<GroupRepresentation> optional = groups.stream().filter(g -> g.getName().equals("grp1")).findFirst();
        assertThat(optional.isPresent(), is(true));
        GroupRepresentation grp1 = optional.get();
        ScopePermissionRepresentation scopePermissionRepresentation = authorizationResource.permissions().scope().findByName("view.members.permission.group." + grp1.getId());
        scopePermissionRepresentation.setPolicies(Collections.singleton(policyRepresentation.getId()));
        scopePermissionRepresentation.setDecisionStrategy(DecisionStrategy.UNANIMOUS);
        authorizationResource.permissions().scope().findById(scopePermissionRepresentation.getId()).update(scopePermissionRepresentation);
    }
    Keycloak testUserClient = AdminClientUtil.createAdminClient(true, realm.toRepresentation().getRealm(), "test-user", "password", "admin-cli", "");
    return testUserClient.realm(realm.toRepresentation().getRealm());
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Profile(org.keycloak.common.Profile) Matchers.not(org.hamcrest.Matchers.not) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) GroupRepresentation(org.keycloak.representations.idm.GroupRepresentation) KeyStoreException(java.security.KeyStoreException) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) ManagementPermissionRepresentation(org.keycloak.representations.idm.ManagementPermissionRepresentation) AdminClientUtil(org.keycloak.testsuite.util.AdminClientUtil) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ProfileAssume(org.keycloak.testsuite.ProfileAssume) Before(org.junit.Before) Matchers.empty(org.hamcrest.Matchers.empty) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test) IOException(java.io.IOException) DecisionStrategy(org.keycloak.representations.idm.authorization.DecisionStrategy) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) Keycloak(org.keycloak.admin.client.Keycloak) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) List(java.util.List) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Optional(java.util.Optional) Collections(java.util.Collections) GroupRepresentation(org.keycloak.representations.idm.GroupRepresentation) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) Keycloak(org.keycloak.admin.client.Keycloak) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation)

Aggregations

PolicyRepresentation (org.keycloak.representations.idm.authorization.PolicyRepresentation)58 Test (org.junit.Test)26 HashMap (java.util.HashMap)20 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)19 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)18 Response (javax.ws.rs.core.Response)15 List (java.util.List)12 Map (java.util.Map)12 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 Collectors (java.util.stream.Collectors)10 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)10 AbstractPolicyRepresentation (org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation)10 ScopeRepresentation (org.keycloak.representations.idm.authorization.ScopeRepresentation)10 UserPolicyRepresentation (org.keycloak.representations.idm.authorization.UserPolicyRepresentation)10 WebElement (org.openqa.selenium.WebElement)10 Set (java.util.Set)9 Policy (org.keycloak.authorization.model.Policy)9 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)9 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)8