Search in sources :

Example 16 with RoleModel

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

the class ApplicationsBean method toApplicationEntry.

/**
 * Constructs a {@link ApplicationEntry} from the specified parameters.
 *
 * @param session a reference to the {@code Keycloak} session.
 * @param realm a reference to the realm.
 * @param user a reference to the user.
 * @param client a reference to the client that contains the applications.
 * @param offlineClients a {@link Set} containing the offline clients.
 * @return the constructed {@link ApplicationEntry} instance or {@code null} if the user can't access the applications
 * in the specified client.
 */
private ApplicationEntry toApplicationEntry(final KeycloakSession session, final RealmModel realm, final UserModel user, final ClientModel client, final Set<ClientModel> offlineClients) {
    // Construct scope parameter with all optional scopes to see all potentially available roles
    Stream<ClientScopeModel> allClientScopes = Stream.concat(client.getClientScopes(true).values().stream(), client.getClientScopes(false).values().stream());
    allClientScopes = Stream.concat(allClientScopes, Stream.of(client)).distinct();
    Set<RoleModel> availableRoles = TokenManager.getAccess(user, client, allClientScopes);
    // unless this is can be changed by approving/revoking consent
    if (!isAdminClient(client) && availableRoles.isEmpty() && !client.isConsentRequired()) {
        return null;
    }
    List<RoleModel> realmRolesAvailable = new LinkedList<>();
    MultivaluedHashMap<String, ClientRoleEntry> resourceRolesAvailable = new MultivaluedHashMap<>();
    processRoles(availableRoles, realmRolesAvailable, resourceRolesAvailable);
    List<ClientScopeModel> orderedScopes = new LinkedList<>();
    if (client.isConsentRequired()) {
        UserConsentModel consent = session.users().getConsentByClient(realm, user.getId(), client.getId());
        if (consent != null) {
            orderedScopes.addAll(consent.getGrantedClientScopes());
        }
    }
    List<String> clientScopesGranted = orderedScopes.stream().sorted(OrderedModel.OrderedModelComparator.getInstance()).map(ClientScopeModel::getConsentScreenText).collect(Collectors.toList());
    List<String> additionalGrants = new ArrayList<>();
    if (offlineClients.contains(client)) {
        additionalGrants.add("${offlineToken}");
    }
    return new ApplicationEntry(session, realmRolesAvailable, resourceRolesAvailable, client, clientScopesGranted, additionalGrants);
}
Also used : ArrayList(java.util.ArrayList) ClientScopeModel(org.keycloak.models.ClientScopeModel) RoleModel(org.keycloak.models.RoleModel) LinkedList(java.util.LinkedList) UserConsentModel(org.keycloak.models.UserConsentModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap)

Example 17 with RoleModel

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

the class ApplicationsBean method processRoles.

private void processRoles(Set<RoleModel> inputRoles, List<RoleModel> realmRoles, MultivaluedHashMap<String, ClientRoleEntry> clientRoles) {
    for (RoleModel role : inputRoles) {
        if (role.getContainer() instanceof RealmModel) {
            realmRoles.add(role);
        } else {
            ClientModel currentClient = (ClientModel) role.getContainer();
            ClientRoleEntry clientRole = new ClientRoleEntry(currentClient.getClientId(), currentClient.getName(), role.getName(), role.getDescription());
            clientRoles.add(currentClient.getClientId(), clientRole);
        }
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) RoleModel(org.keycloak.models.RoleModel)

Example 18 with RoleModel

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

the class RoleLDAPStorageMapper method syncDataFromKeycloakToFederationProvider.

// Sync roles from Keycloak back to LDAP
@Override
public SynchronizationResult syncDataFromKeycloakToFederationProvider(RealmModel realm) {
    SynchronizationResult syncResult = new SynchronizationResult() {

        @Override
        public String getStatus() {
            return String.format("%d roles imported to LDAP, %d roles already existed in LDAP", getAdded(), getUpdated());
        }
    };
    if (config.getMode() != LDAPGroupMapperMode.LDAP_ONLY) {
        logger.warnf("Ignored sync for federation mapper '%s' as it's mode is '%s'", mapperModel.getName(), config.getMode().toString());
        return syncResult;
    }
    logger.debugf("Syncing roles from Keycloak into LDAP. Mapper is [%s], LDAP provider is [%s]", mapperModel.getName(), ldapProvider.getModel().getName());
    // Send LDAP query to see which roles exists there
    try (LDAPQuery ldapQuery = createRoleQuery(false)) {
        List<LDAPObject> ldapRoles = LDAPUtils.loadAllLDAPObjects(ldapQuery, ldapProvider);
        Set<String> ldapRoleNames = new HashSet<>();
        String rolesRdnAttr = config.getRoleNameLdapAttribute();
        for (LDAPObject ldapRole : ldapRoles) {
            String roleName = ldapRole.getAttributeAsString(rolesRdnAttr);
            ldapRoleNames.add(roleName);
        }
        RoleContainerModel roleContainer = getTargetRoleContainer(realm);
        Stream<RoleModel> keycloakRoles = roleContainer.getRolesStream();
        Consumer<String> syncRoleFromKCToLDAP = roleName -> {
            if (ldapRoleNames.contains(roleName)) {
                syncResult.increaseUpdated();
            } else {
                logger.debugf("Syncing role [%s] from Keycloak to LDAP", roleName);
                createLDAPRole(roleName);
                syncResult.increaseAdded();
            }
        };
        keycloakRoles.map(RoleModel::getName).forEach(syncRoleFromKCToLDAP);
        return syncResult;
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel) AbstractLDAPStorageMapper(org.keycloak.storage.ldap.mappers.AbstractLDAPStorageMapper) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) Logger(org.jboss.logging.Logger) RoleContainerModel(org.keycloak.models.RoleContainerModel) RoleUtils(org.keycloak.models.utils.RoleUtils) HashSet(java.util.HashSet) UserRolesRetrieveStrategy(org.keycloak.storage.ldap.mappers.membership.UserRolesRetrieveStrategy) UserModel(org.keycloak.models.UserModel) ComponentModel(org.keycloak.component.ComponentModel) LDAPGroupMapperMode(org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode) UserModelDelegate(org.keycloak.models.utils.UserModelDelegate) MembershipType(org.keycloak.storage.ldap.mappers.membership.MembershipType) LDAPQueryConditionsBuilder(org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder) RealmModel(org.keycloak.models.RealmModel) LDAPConfig(org.keycloak.storage.ldap.LDAPConfig) Collection(java.util.Collection) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) LDAPQuery(org.keycloak.storage.ldap.idm.query.internal.LDAPQuery) Collectors(java.util.stream.Collectors) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) Objects(java.util.Objects) Consumer(java.util.function.Consumer) List(java.util.List) Stream(java.util.stream.Stream) LDAPUtils(org.keycloak.storage.ldap.LDAPUtils) ModelException(org.keycloak.models.ModelException) CommonLDAPGroupMapperConfig(org.keycloak.storage.ldap.mappers.membership.CommonLDAPGroupMapperConfig) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) CommonLDAPGroupMapper(org.keycloak.storage.ldap.mappers.membership.CommonLDAPGroupMapper) Collections(java.util.Collections) Condition(org.keycloak.storage.ldap.idm.query.Condition) LDAPQuery(org.keycloak.storage.ldap.idm.query.internal.LDAPQuery) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) RoleModel(org.keycloak.models.RoleModel) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) RoleContainerModel(org.keycloak.models.RoleContainerModel) HashSet(java.util.HashSet)

Example 19 with RoleModel

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

the class RoleLDAPStorageMapper method onImportUserFromLDAP.

@Override
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) {
    LDAPGroupMapperMode mode = config.getMode();
    // For now, import LDAP role mappings just during create
    if (mode == LDAPGroupMapperMode.IMPORT && isCreate) {
        List<LDAPObject> ldapRoles = getLDAPRoleMappings(ldapUser);
        // Import role mappings from LDAP into Keycloak DB
        String roleNameAttr = config.getRoleNameLdapAttribute();
        for (LDAPObject ldapRole : ldapRoles) {
            String roleName = ldapRole.getAttributeAsString(roleNameAttr);
            RoleContainerModel roleContainer = getTargetRoleContainer(realm);
            RoleModel role = roleContainer.getRole(roleName);
            if (role == null) {
                role = roleContainer.addRole(roleName);
            }
            logger.debugf("Granting role [%s] to user [%s] during import from LDAP", roleName, user.getUsername());
            user.grantRole(role);
        }
    }
}
Also used : LDAPGroupMapperMode(org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) RoleModel(org.keycloak.models.RoleModel) RoleContainerModel(org.keycloak.models.RoleContainerModel)

Example 20 with RoleModel

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

the class JpaRealmProviderFactory method onEvent.

@Override
public void onEvent(ProviderEvent event) {
    if (event instanceof RoleContainerModel.RoleRemovedEvent) {
        RoleRemovedEvent e = (RoleContainerModel.RoleRemovedEvent) event;
        RoleModel role = e.getRole();
        RoleContainerModel container = role.getContainer();
        RealmModel realm;
        if (container instanceof RealmModel) {
            realm = (RealmModel) container;
        } else if (container instanceof ClientModel) {
            realm = ((ClientModel) container).getRealm();
        } else {
            return;
        }
        ((JpaRealmProvider) e.getKeycloakSession().getProvider(RealmProvider.class)).preRemove(realm, role);
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) RealmProvider(org.keycloak.models.RealmProvider) RoleRemovedEvent(org.keycloak.models.RoleContainerModel.RoleRemovedEvent) RoleModel(org.keycloak.models.RoleModel) RoleContainerModel(org.keycloak.models.RoleContainerModel)

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