Search in sources :

Example 6 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider 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 7 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class RegexPolicyProvider method evaluate.

@Override
public void evaluate(Evaluation evaluation) {
    AuthorizationProvider authorizationProvider = evaluation.getAuthorizationProvider();
    RegexPolicyRepresentation policy = representationFunction.apply(evaluation.getPolicy(), authorizationProvider);
    Attributes.Entry targetClaim = evaluation.getContext().getIdentity().getAttributes().getValue(policy.getTargetClaim());
    if (targetClaim == null) {
        return;
    }
    Pattern pattern = Pattern.compile(policy.getPattern());
    Matcher matcher = pattern.matcher(targetClaim.asString(0));
    if (matcher.matches()) {
        evaluation.grant();
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) RegexPolicyRepresentation(org.keycloak.representations.idm.authorization.RegexPolicyRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Attributes(org.keycloak.authorization.attribute.Attributes)

Example 8 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class RepresentationToModel method createResourceServer.

public static ResourceServer createResourceServer(ClientModel client, KeycloakSession session, boolean addDefaultRoles) {
    if ((client.isBearerOnly() || client.isPublicClient()) && !(client.getClientId().equals(Config.getAdminRealm() + "-realm") || client.getClientId().equals(Constants.REALM_MANAGEMENT_CLIENT_ID))) {
        throw new RuntimeException("Only confidential clients are allowed to set authorization settings");
    }
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    UserModel serviceAccount = session.users().getServiceAccount(client);
    if (serviceAccount == null) {
        client.setServiceAccountsEnabled(true);
    }
    if (addDefaultRoles) {
        RoleModel umaProtectionRole = client.getRole(Constants.AUTHZ_UMA_PROTECTION);
        if (umaProtectionRole == null) {
            umaProtectionRole = client.addRole(Constants.AUTHZ_UMA_PROTECTION);
        }
        if (serviceAccount != null) {
            serviceAccount.grantRole(umaProtectionRole);
        }
    }
    ResourceServerRepresentation representation = new ResourceServerRepresentation();
    representation.setAllowRemoteResourceManagement(true);
    representation.setClientId(client.getId());
    return toModel(representation, authorization, client);
}
Also used : UserModel(org.keycloak.models.UserModel) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) RoleModel(org.keycloak.models.RoleModel)

Example 9 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class FineGrainAdminUnitTest method testClientsSearchAfterFirstPage.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testClientsSearchAfterFirstPage() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        session.getContext().setRealm(realm);
        ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
        UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user");
        session.userCredentialManager().updateCredential(realm, regularAdminUser, UserCredentialModel.password("password"));
        regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_CLIENTS));
        regularAdminUser.setEnabled(true);
        UserPolicyRepresentation userPolicyRepresentation = new UserPolicyRepresentation();
        userPolicyRepresentation.setName("Only " + regularAdminUser.getUsername());
        userPolicyRepresentation.addUser(regularAdminUser.getId());
        AdminPermissionManagement management = AdminPermissions.management(session, realm);
        ClientPermissionManagement clientPermission = management.clients();
        for (int i = 15; i < 30; i++) {
            ClientModel clientModel = realm.addClient("client-search-" + (i < 10 ? "0" + i : i));
            clientPermission.setPermissionsEnabled(clientModel, true);
            Policy policy = clientPermission.viewPermission(clientModel);
            AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
            if (i == 15) {
                provider.getStoreFactory().getPolicyStore().create(userPolicyRepresentation, management.realmResourceServer());
            }
            policy.addAssociatedPolicy(provider.getStoreFactory().getPolicyStore().findByName("Only regular-admin-user", realmAdminClient.getId()));
        }
    });
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<ClientRepresentation> clients = new ArrayList<>();
        List<ClientRepresentation> result = client.realm("test").clients().findAll("client-search-", true, true, 0, 10);
        clients.addAll(result);
        Assert.assertEquals(10, result.size());
        Assert.assertThat(result.stream().map(rep -> rep.getClientId()).collect(Collectors.toList()), Matchers.is(Arrays.asList("client-search-15", "client-search-16", "client-search-17", "client-search-18", "client-search-19", "client-search-20", "client-search-21", "client-search-22", "client-search-23", "client-search-24")));
        result = client.realm("test").clients().findAll("client-search-", true, true, 10, 10);
        clients.addAll(result);
        Assert.assertEquals(5, result.size());
        Assert.assertThat(result.stream().map(rep -> rep.getClientId()).collect(Collectors.toList()), Matchers.is(Arrays.asList("client-search-25", "client-search-26", "client-search-27", "client-search-28", "client-search-29")));
        result = client.realm("test").clients().findAll("client-search-", true, true, 20, 10);
        clients.addAll(result);
        Assert.assertTrue(result.isEmpty());
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ArrayList(java.util.ArrayList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) ClientPermissionManagement(org.keycloak.services.resources.admin.permissions.ClientPermissionManagement) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) Keycloak(org.keycloak.admin.client.Keycloak) AdminPermissionManagement(org.keycloak.services.resources.admin.permissions.AdminPermissionManagement) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 10 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class AuthzCleanupTest method setup.

public static void setup(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    session.getContext().setRealm(realm);
    AuthorizationProvider authz = session.getProvider(AuthorizationProvider.class);
    ClientModel myclient = realm.getClientByClientId("myclient");
    ResourceServer resourceServer = authz.getStoreFactory().getResourceServerStore().findByClient(myclient);
    createRolePolicy(authz, resourceServer, myclient.getClientId() + "/client-role-1");
    createRolePolicy(authz, resourceServer, myclient.getClientId() + "/client-role-2");
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Aggregations

AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)60 Policy (org.keycloak.authorization.model.Policy)35 ClientModel (org.keycloak.models.ClientModel)35 ResourceServer (org.keycloak.authorization.model.ResourceServer)30 StoreFactory (org.keycloak.authorization.store.StoreFactory)24 RealmModel (org.keycloak.models.RealmModel)23 HashMap (java.util.HashMap)18 UserModel (org.keycloak.models.UserModel)18 Resource (org.keycloak.authorization.model.Resource)16 PolicyProvider (org.keycloak.authorization.policy.provider.PolicyProvider)15 ArrayList (java.util.ArrayList)14 Map (java.util.Map)14 Scope (org.keycloak.authorization.model.Scope)13 List (java.util.List)12 DefaultEvaluation (org.keycloak.authorization.policy.evaluation.DefaultEvaluation)12 KeycloakSession (org.keycloak.models.KeycloakSession)12 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)11 Set (java.util.Set)10 Collectors (java.util.stream.Collectors)10 HashSet (java.util.HashSet)9