Search in sources :

Example 46 with RoleModel

use of org.keycloak.models.RoleModel in project keycloak by keycloak.

the class MigrateTo3_2_0 method addRoles.

public void addRoles(ClientModel realmAccess) {
    RoleModel queryClients = realmAccess.getRole(AdminRoles.QUERY_CLIENTS);
    if (queryClients == null) {
        queryClients = realmAccess.addRole(AdminRoles.QUERY_CLIENTS);
        RoleModel viewClients = realmAccess.getRole(AdminRoles.VIEW_CLIENTS);
        if (viewClients != null) {
            viewClients.addCompositeRole(queryClients);
        }
    }
    RoleModel queryUsers = realmAccess.getRole(AdminRoles.QUERY_USERS);
    if (queryUsers == null)
        queryUsers = realmAccess.addRole(AdminRoles.QUERY_USERS);
    RoleModel queryGroups = realmAccess.getRole(AdminRoles.QUERY_GROUPS);
    if (queryGroups == null)
        queryGroups = realmAccess.addRole(AdminRoles.QUERY_GROUPS);
    RoleModel viewUsers = realmAccess.getRole(AdminRoles.VIEW_USERS);
    if (viewUsers != null) {
        if (!viewUsers.hasRole(queryUsers))
            viewUsers.addCompositeRole(queryUsers);
        if (!viewUsers.hasRole(queryGroups))
            viewUsers.addCompositeRole(queryGroups);
    }
}
Also used : RoleModel(org.keycloak.models.RoleModel)

Example 47 with RoleModel

use of org.keycloak.models.RoleModel in project keycloak by keycloak.

the class MigrateTo4_0_0 method migrateRealm.

protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
    // Upgrade names of clientScopes to not contain space
    realm.getClientScopesStream().filter(clientScope -> clientScope.getName().contains(" ")).forEach(clientScope -> {
        LOG.debugf("Replacing spaces with underscores in the name of client scope '%s' of realm '%s'", clientScope.getName(), realm.getName());
        String replacedName = clientScope.getName().replaceAll(" ", "_");
        clientScope.setName(replacedName);
    });
    if (!json) {
        // Add default client scopes. But don't add them to existing clients. For JSON, they were already added
        LOG.debugf("Adding defaultClientScopes for realm '%s'", realm.getName());
        DefaultClientScopes.createDefaultClientScopes(session, realm, false);
    }
    // Upgrade configuration of "allowed-client-templates" client registration policy
    realm.getComponentsStream(realm.getId(), "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy").filter(component -> Objects.equals(component.getProviderId(), "allowed-client-templates")).forEach(component -> {
        List<String> configVal = component.getConfig().remove("allowed-client-templates");
        if (configVal != null) {
            component.getConfig().put("allowed-client-scopes", configVal);
        }
        component.put("allow-default-scopes", true);
        realm.updateComponent(component);
    });
    // If client has scope for offline_access role (either directly or through fullScopeAllowed), then add offline_access client
    // scope as optional scope to the client. If it's indirectly (no fullScopeAllowed), then remove role from the scoped roles
    RoleModel offlineAccessRole = realm.getRole(OAuth2Constants.OFFLINE_ACCESS);
    ClientScopeModel offlineAccessScope;
    if (offlineAccessRole == null) {
        LOG.infof("Role 'offline_access' not available in realm '%s'. Skip migration of offline_access client scope.", realm.getName());
    } else {
        offlineAccessScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
        if (offlineAccessScope == null) {
            LOG.infof("Client scope 'offline_access' not available in realm '%s'. Skip migration of offline_access client scope.", realm.getName());
        } else {
            realm.getClientsStream().filter(MigrationUtils::isOIDCNonBearerOnlyClient).filter(c -> c.hasScope(offlineAccessRole)).filter(c -> !c.getClientScopes(false).containsKey(OAuth2Constants.OFFLINE_ACCESS)).peek(c -> {
                LOG.debugf("Adding client scope 'offline_access' as optional scope to client '%s' in realm '%s'.", c.getClientId(), realm.getName());
                c.addClientScope(offlineAccessScope, false);
            }).filter(c -> !c.isFullScopeAllowed()).forEach(c -> {
                LOG.debugf("Removing role scope mapping for role 'offline_access' from client '%s' in realm '%s'.", c.getClientId(), realm.getName());
                c.deleteScopeMapping(offlineAccessRole);
            });
        }
    }
    // Clients with consentRequired, which don't have any client scopes will be added itself to require consent, so that consent screen is shown when users authenticate
    realm.getClientsStream().filter(ClientModel::isConsentRequired).filter(c -> c.getClientScopes(true).isEmpty()).forEach(c -> {
        LOG.debugf("Adding client '%s' of realm '%s' to display itself on consent screen", c.getClientId(), realm.getName());
        c.setDisplayOnConsentScreen(true);
        String consentText = c.getName() == null ? c.getClientId() : c.getName();
        c.setConsentScreenText(consentText);
    });
}
Also used : ClientModel(org.keycloak.models.ClientModel) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) Objects(java.util.Objects) List(java.util.List) DefaultClientScopes(org.keycloak.models.utils.DefaultClientScopes) ModelVersion(org.keycloak.migration.ModelVersion) OAuth2Constants(org.keycloak.OAuth2Constants) ClientModel(org.keycloak.models.ClientModel) RoleModel(org.keycloak.models.RoleModel) ClientScopeModel(org.keycloak.models.ClientScopeModel)

Example 48 with RoleModel

use of org.keycloak.models.RoleModel in project keycloak by keycloak.

the class MigrateTo1_6_0 method migrateRealm.

protected void migrateRealm(KeycloakSession session, ProtocolMapperModel localeMapper, RealmModel realm) {
    realm.setOfflineSessionIdleTimeout(Constants.DEFAULT_OFFLINE_SESSION_IDLE_TIMEOUT);
    if (realm.getRole(Constants.OFFLINE_ACCESS_ROLE) == null) {
        KeycloakModelUtils.setupOfflineRole(realm);
        RoleModel role = realm.getRole(Constants.OFFLINE_ACCESS_ROLE);
        // Bulk grant of offline_access role to all users
        session.users().grantToAllUsers(realm, role);
    }
    ClientModel adminConsoleClient = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
    if ((adminConsoleClient != null) && !localeMapperAdded(adminConsoleClient)) {
        adminConsoleClient.addProtocolMapper(localeMapper);
    }
    ClientModel client = realm.getMasterAdminClient();
    if (client.getRole(AdminRoles.CREATE_CLIENT) == null) {
        RoleModel role = client.addRole(AdminRoles.CREATE_CLIENT);
        role.setDescription("${role_" + AdminRoles.CREATE_CLIENT + "}");
        client.getRealm().getRole(AdminRoles.ADMIN).addCompositeRole(role);
    }
    if (!realm.getName().equals(Config.getAdminRealm())) {
        client = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
        if (client.getRole(AdminRoles.CREATE_CLIENT) == null) {
            RoleModel role = client.addRole(AdminRoles.CREATE_CLIENT);
            role.setDescription("${role_" + AdminRoles.CREATE_CLIENT + "}");
            client.getRole(AdminRoles.REALM_ADMIN).addCompositeRole(role);
        }
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel) RoleModel(org.keycloak.models.RoleModel)

Example 49 with RoleModel

use of org.keycloak.models.RoleModel in project keycloak by keycloak.

the class RoleUtils method expandCompositeRolesStream.

/**
 * Recursively expands composite roles into their composite.
 * @param role
 * @param visited Track roles, which were already visited. Those will be ignored and won't be added to the stream. Besides that,
 *                the "visited" set itself will be updated as a result of this method call and all the tracked roles will be added to it
 * @return Stream of containing all of the composite roles and their components. Never returns {@code null}.
 */
private static Stream<RoleModel> expandCompositeRolesStream(RoleModel role, Set<RoleModel> visited) {
    Stream.Builder<RoleModel> sb = Stream.builder();
    if (!visited.contains(role)) {
        Deque<RoleModel> stack = new ArrayDeque<>();
        stack.add(role);
        while (!stack.isEmpty()) {
            RoleModel current = stack.pop();
            sb.add(current);
            if (current.isComposite()) {
                current.getCompositesStream().filter(r -> !visited.contains(r)).forEach(r -> {
                    visited.add(r);
                    stack.add(r);
                });
            }
        }
    }
    return sb.build();
}
Also used : ClientModel(org.keycloak.models.ClientModel) RealmModel(org.keycloak.models.RealmModel) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) RoleContainerModel(org.keycloak.models.RoleContainerModel) Deque(java.util.Deque) Collectors(java.util.stream.Collectors) HashSet(java.util.HashSet) Objects(java.util.Objects) UserModel(org.keycloak.models.UserModel) Stream(java.util.stream.Stream) GroupModel(org.keycloak.models.GroupModel) StreamSupport(java.util.stream.StreamSupport) ArrayDeque(java.util.ArrayDeque) Stream(java.util.stream.Stream) RoleModel(org.keycloak.models.RoleModel) ArrayDeque(java.util.ArrayDeque)

Example 50 with RoleModel

use of org.keycloak.models.RoleModel in project keycloak by keycloak.

the class ClientModelIdentity method hasClientRole.

@Override
public boolean hasClientRole(String clientId, String roleName) {
    if (serviceAccount == null)
        return false;
    ClientModel client = realm.getClientByClientId(clientId);
    RoleModel role = client.getRole(roleName);
    if (role == null)
        return false;
    return serviceAccount.hasRole(role);
}
Also used : ClientModel(org.keycloak.models.ClientModel) RoleModel(org.keycloak.models.RoleModel)

Aggregations

RoleModel (org.keycloak.models.RoleModel)153 ClientModel (org.keycloak.models.ClientModel)73 RealmModel (org.keycloak.models.RealmModel)69 UserModel (org.keycloak.models.UserModel)36 Path (javax.ws.rs.Path)29 Test (org.junit.Test)29 NotFoundException (javax.ws.rs.NotFoundException)25 NoCache (org.jboss.resteasy.annotations.cache.NoCache)20 KeycloakSession (org.keycloak.models.KeycloakSession)19 Consumes (javax.ws.rs.Consumes)17 List (java.util.List)16 GET (javax.ws.rs.GET)16 Produces (javax.ws.rs.Produces)16 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)15 LinkedList (java.util.LinkedList)14 HashMap (java.util.HashMap)13 ArrayList (java.util.ArrayList)12 GroupModel (org.keycloak.models.GroupModel)12 RoleContainerModel (org.keycloak.models.RoleContainerModel)12 Policy (org.keycloak.authorization.model.Policy)11