Search in sources :

Example 6 with ModelToRepresentation

use of org.keycloak.models.utils.ModelToRepresentation in project keycloak by keycloak.

the class ClientRoleMappingsResource method deleteClientRoleMapping.

/**
 * Delete client-level roles from user role mapping
 *
 * @param roles
 */
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public void deleteClientRoleMapping(List<RoleRepresentation> roles) {
    managePermission.require();
    if (roles == null) {
        roles = user.getClientRoleMappingsStream(client).peek(roleModel -> {
            auth.roles().requireMapRole(roleModel);
            user.deleteRoleMapping(roleModel);
        }).map(ModelToRepresentation::toBriefRepresentation).collect(Collectors.toList());
    } else {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = client.getRole(role.getName());
            if (roleModel == null || !roleModel.getId().equals(role.getId())) {
                throw new NotFoundException("Role not found");
            }
            auth.roles().requireMapRole(roleModel);
            try {
                user.deleteRoleMapping(roleModel);
            } catch (ModelException | ReadOnlyException me) {
                logger.warn(me.getMessage(), me);
                throw new ErrorResponseException("invalid_request", "Could not remove user role mappings!", Response.Status.BAD_REQUEST);
            }
        }
    }
    adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).representation(roles).success();
}
Also used : ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Path(javax.ws.rs.Path) Function(java.util.function.Function) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) ErrorResponseException(org.keycloak.services.ErrorResponseException) DefaultValue(javax.ws.rs.DefaultValue) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) POST(javax.ws.rs.POST) Predicate(java.util.function.Predicate) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) Stream(java.util.stream.Stream) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) ModelException(org.keycloak.models.ModelException) RoleMapperModel(org.keycloak.models.RoleMapperModel) UriInfo(javax.ws.rs.core.UriInfo) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ModelException(org.keycloak.models.ModelException) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) ReadOnlyException(org.keycloak.storage.ReadOnlyException) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes)

Example 7 with ModelToRepresentation

use of org.keycloak.models.utils.ModelToRepresentation in project keycloak by keycloak.

the class DefaultEvaluation method createRealm.

private Realm createRealm() {
    return new Realm() {

        @Override
        public boolean isUserInGroup(String id, String groupId, boolean checkParent) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            RealmModel realm = session.getContext().getRealm();
            GroupModel group = KeycloakModelUtils.findGroupByPath(realm, groupId);
            if (Objects.isNull(group)) {
                return false;
            }
            if (checkParent) {
                return RoleUtils.isMember(user.getGroupsStream(), group);
            }
            return user.isMemberOf(group);
        }

        private UserModel getUser(String id, KeycloakSession session) {
            RealmModel realm = session.getContext().getRealm();
            UserModel user = session.users().getUserById(realm, id);
            if (Objects.isNull(user)) {
                user = session.users().getUserByUsername(realm, id);
            }
            if (Objects.isNull(user)) {
                user = session.users().getUserByEmail(realm, id);
            }
            if (Objects.isNull(user)) {
                user = session.users().getServiceAccount(realm.getClientById(id));
            }
            return user;
        }

        @Override
        public boolean isUserInRealmRole(String id, String roleName) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            Stream<RoleModel> roleMappings = user.getRoleMappingsStream().filter(isNotClientRole);
            return RoleUtils.hasRole(roleMappings, session.getContext().getRealm().getRole(roleName));
        }

        @Override
        public boolean isUserInClientRole(String id, String clientId, String roleName) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            RealmModel realm = session.getContext().getRealm();
            UserModel user = getUser(id, session);
            if (Objects.isNull(user)) {
                return false;
            }
            Set<RoleModel> roleMappings = user.getRoleMappingsStream().filter(RoleModel::isClientRole).filter(role -> Objects.equals(((ClientModel) role.getContainer()).getClientId(), clientId)).collect(Collectors.toSet());
            if (roleMappings.isEmpty()) {
                return false;
            }
            RoleModel role = realm.getClientById(roleMappings.iterator().next().getContainer().getId()).getRole(roleName);
            if (Objects.isNull(role)) {
                return false;
            }
            return RoleUtils.hasRole(roleMappings, role);
        }

        @Override
        public boolean isGroupInRole(String id, String role) {
            KeycloakSession session = authorizationProvider.getKeycloakSession();
            RealmModel realm = session.getContext().getRealm();
            GroupModel group = KeycloakModelUtils.findGroupByPath(realm, id);
            return RoleUtils.hasRoleFromGroup(group, realm.getRole(role), false);
        }

        @Override
        public List<String> getUserRealmRoles(String id) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(isNotClientRole).map(RoleModel::getName).collect(Collectors.toList());
        }

        @Override
        public List<String> getUserClientRoles(String id, String clientId) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(RoleModel::isClientRole).map(RoleModel::getName).collect(Collectors.toList());
        }

        @Override
        public List<String> getUserGroups(String id) {
            return getUser(id, authorizationProvider.getKeycloakSession()).getGroupsStream().map(ModelToRepresentation::buildGroupPath).collect(Collectors.toList());
        }

        @Override
        public Map<String, List<String>> getUserAttributes(String id) {
            return Collections.unmodifiableMap(getUser(id, authorizationProvider.getKeycloakSession()).getAttributes());
        }
    };
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) ClientModel(org.keycloak.models.ClientModel) java.util(java.util) Effect(org.keycloak.authorization.Decision.Effect) RealmModel(org.keycloak.models.RealmModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Predicate(java.util.function.Predicate) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) Decision(org.keycloak.authorization.Decision) Collectors(java.util.stream.Collectors) RoleUtils(org.keycloak.models.utils.RoleUtils) Policy(org.keycloak.authorization.model.Policy) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) Stream(java.util.stream.Stream) UserModel(org.keycloak.models.UserModel) Logic(org.keycloak.representations.idm.authorization.Logic) GroupModel(org.keycloak.models.GroupModel) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) KeycloakSession(org.keycloak.models.KeycloakSession) GroupModel(org.keycloak.models.GroupModel) RoleModel(org.keycloak.models.RoleModel)

Example 8 with ModelToRepresentation

use of org.keycloak.models.utils.ModelToRepresentation in project keycloak by keycloak.

the class ExportUtils method exportRealm.

public static RealmRepresentation exportRealm(KeycloakSession session, RealmModel realm, ExportOptions options, boolean internal) {
    RealmRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, internal);
    ModelToRepresentation.exportAuthenticationFlows(realm, rep);
    ModelToRepresentation.exportRequiredActions(realm, rep);
    // Project/product version
    rep.setKeycloakVersion(Version.VERSION_KEYCLOAK);
    // Client Scopes
    rep.setClientScopes(realm.getClientScopesStream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList()));
    rep.setDefaultDefaultClientScopes(realm.getDefaultClientScopesStream(true).map(ClientScopeModel::getName).collect(Collectors.toList()));
    rep.setDefaultOptionalClientScopes(realm.getDefaultClientScopesStream(false).map(ClientScopeModel::getName).collect(Collectors.toList()));
    // Clients
    List<ClientModel> clients = new LinkedList<>();
    if (options.isClientsIncluded()) {
        // we iterate over all clients in the stream.
        // only those client models that can be translated into a valid client representation will be added to the client list
        // that is later used to retrieve related information about groups and roles
        List<ClientRepresentation> clientReps = ModelToRepresentation.filterValidRepresentations(realm.getClientsStream(), app -> {
            ClientRepresentation clientRepresentation = exportClient(session, app);
            clients.add(app);
            return clientRepresentation;
        }).collect(Collectors.toList());
        rep.setClients(clientReps);
    }
    // Groups and Roles
    if (options.isGroupsAndRolesIncluded()) {
        ModelToRepresentation.exportGroups(realm, rep);
        Map<String, List<RoleRepresentation>> clientRolesReps = new HashMap<>();
        List<RoleRepresentation> realmRoleReps = exportRoles(realm.getRolesStream());
        RolesRepresentation rolesRep = new RolesRepresentation();
        if (!realmRoleReps.isEmpty()) {
            rolesRep.setRealm(realmRoleReps);
        }
        if (options.isClientsIncluded()) {
            for (ClientModel client : clients) {
                Stream<RoleModel> currentAppRoles = client.getRolesStream();
                List<RoleRepresentation> currentAppRoleReps = exportRoles(currentAppRoles);
                clientRolesReps.put(client.getClientId(), currentAppRoleReps);
            }
            if (clientRolesReps.size() > 0) {
                rolesRep.setClient(clientRolesReps);
            }
        }
        rep.setRoles(rolesRep);
    }
    // Scopes
    Map<String, List<ScopeMappingRepresentation>> clientScopeReps = new HashMap<>();
    if (options.isClientsIncluded()) {
        List<ClientModel> allClients = new ArrayList<>(clients);
        // Scopes of clients
        for (ClientModel client : allClients) {
            Set<RoleModel> clientScopes = client.getScopeMappingsStream().collect(Collectors.toSet());
            ScopeMappingRepresentation scopeMappingRep = null;
            for (RoleModel scope : clientScopes) {
                if (scope.getContainer() instanceof RealmModel) {
                    if (scopeMappingRep == null) {
                        scopeMappingRep = rep.clientScopeMapping(client.getClientId());
                    }
                    scopeMappingRep.role(scope.getName());
                } else {
                    ClientModel app = (ClientModel) scope.getContainer();
                    String appName = app.getClientId();
                    List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
                    if (currentAppScopes == null) {
                        currentAppScopes = new ArrayList<>();
                        clientScopeReps.put(appName, currentAppScopes);
                    }
                    ScopeMappingRepresentation currentClientScope = null;
                    for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
                        if (client.getClientId().equals(scopeMapping.getClient())) {
                            currentClientScope = scopeMapping;
                            break;
                        }
                    }
                    if (currentClientScope == null) {
                        currentClientScope = new ScopeMappingRepresentation();
                        currentClientScope.setClient(client.getClientId());
                        currentAppScopes.add(currentClientScope);
                    }
                    currentClientScope.role(scope.getName());
                }
            }
        }
    }
    // Scopes of client scopes
    realm.getClientScopesStream().forEach(clientScope -> {
        Set<RoleModel> clientScopes = clientScope.getScopeMappingsStream().collect(Collectors.toSet());
        ScopeMappingRepresentation scopeMappingRep = null;
        for (RoleModel scope : clientScopes) {
            if (scope.getContainer() instanceof RealmModel) {
                if (scopeMappingRep == null) {
                    scopeMappingRep = rep.clientScopeScopeMapping(clientScope.getName());
                }
                scopeMappingRep.role(scope.getName());
            } else {
                ClientModel app = (ClientModel) scope.getContainer();
                String appName = app.getClientId();
                List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
                if (currentAppScopes == null) {
                    currentAppScopes = new ArrayList<>();
                    clientScopeReps.put(appName, currentAppScopes);
                }
                ScopeMappingRepresentation currentClientTemplateScope = null;
                for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
                    if (clientScope.getName().equals(scopeMapping.getClientScope())) {
                        currentClientTemplateScope = scopeMapping;
                        break;
                    }
                }
                if (currentClientTemplateScope == null) {
                    currentClientTemplateScope = new ScopeMappingRepresentation();
                    currentClientTemplateScope.setClientScope(clientScope.getName());
                    currentAppScopes.add(currentClientTemplateScope);
                }
                currentClientTemplateScope.role(scope.getName());
            }
        }
    });
    if (clientScopeReps.size() > 0) {
        rep.setClientScopeMappings(clientScopeReps);
    }
    // Finally users if needed
    if (options.isUsersIncluded()) {
        List<UserRepresentation> users = session.users().getUsersStream(realm, true).map(user -> exportUser(session, realm, user, options, internal)).collect(Collectors.toList());
        if (users.size() > 0) {
            rep.setUsers(users);
        }
        List<UserRepresentation> federatedUsers = session.userFederatedStorage().getStoredUsersStream(realm, 0, -1).map(user -> exportFederatedUser(session, realm, user, options)).collect(Collectors.toList());
        if (federatedUsers.size() > 0) {
            rep.setFederatedUsers(federatedUsers);
        }
    } else if (options.isClientsIncluded() && options.isOnlyServiceAccountsIncluded()) {
        List<UserRepresentation> users = new LinkedList<>();
        for (ClientModel app : clients) {
            if (app.isServiceAccountsEnabled() && !app.isPublicClient() && !app.isBearerOnly()) {
                UserModel user = session.users().getServiceAccount(app);
                if (user != null) {
                    UserRepresentation userRep = exportUser(session, realm, user, options, internal);
                    users.add(userRep);
                }
            }
        }
        if (users.size() > 0) {
            rep.setUsers(users);
        }
    }
    // components
    MultivaluedHashMap<String, ComponentExportRepresentation> components = exportComponents(realm, realm.getId());
    rep.setComponents(components);
    return rep;
}
Also used : 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) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) HashMap(java.util.HashMap) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) ScopeMappingRepresentation(org.keycloak.representations.idm.ScopeMappingRepresentation) ArrayList(java.util.ArrayList) ClientScopeModel(org.keycloak.models.ClientScopeModel) RoleModel(org.keycloak.models.RoleModel) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) RolesRepresentation(org.keycloak.representations.idm.RolesRepresentation) ComponentExportRepresentation(org.keycloak.representations.idm.ComponentExportRepresentation) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) LinkedList(java.util.LinkedList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientModel(org.keycloak.models.ClientModel)

Example 9 with ModelToRepresentation

use of org.keycloak.models.utils.ModelToRepresentation in project keycloak by keycloak.

the class RoleMapperResource method deleteRealmRoleMappings.

/**
 * Delete realm-level role mappings
 *
 * @param roles
 */
@Path("realm")
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public void deleteRealmRoleMappings(List<RoleRepresentation> roles) {
    managePermission.require();
    logger.debug("deleteRealmRoleMappings");
    if (roles == null) {
        roles = roleMapper.getRealmRoleMappingsStream().peek(roleModel -> {
            auth.roles().requireMapRole(roleModel);
            roleMapper.deleteRoleMapping(roleModel);
        }).map(ModelToRepresentation::toBriefRepresentation).collect(Collectors.toList());
    } else {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = realm.getRole(role.getName());
            if (roleModel == null || !roleModel.getId().equals(role.getId())) {
                throw new NotFoundException("Role not found");
            }
            auth.roles().requireMapRole(roleModel);
            try {
                roleMapper.deleteRoleMapping(roleModel);
            } catch (ModelException | ReadOnlyException me) {
                logger.warn(me.getMessage(), me);
                throw new ErrorResponseException("invalid_request", "Could not remove user role mappings!", Response.Status.BAD_REQUEST);
            }
        }
    }
    adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).representation(roles).success();
}
Also used : ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) PathParam(javax.ws.rs.PathParam) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Path(javax.ws.rs.Path) HashMap(java.util.HashMap) RoleContainerModel(org.keycloak.models.RoleContainerModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) ClientConnection(org.keycloak.common.ClientConnection) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Predicate(java.util.function.Predicate) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) MappingsRepresentation(org.keycloak.representations.idm.MappingsRepresentation) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Stream(java.util.stream.Stream) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) ClientMappingsRepresentation(org.keycloak.representations.idm.ClientMappingsRepresentation) ModelException(org.keycloak.models.ModelException) RoleMapperModel(org.keycloak.models.RoleMapperModel) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ModelException(org.keycloak.models.ModelException) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes)

Example 10 with ModelToRepresentation

use of org.keycloak.models.utils.ModelToRepresentation in project keycloak by keycloak.

the class ScopeMappedClientResource method deleteClientScopeMapping.

/**
 * Remove client-level roles from the client's scope.
 *
 * @param roles
 */
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public void deleteClientScopeMapping(List<RoleRepresentation> roles) {
    managePermission.require();
    if (roles == null) {
        roles = KeycloakModelUtils.getClientScopeMappingsStream(scopedClient, scopeContainer).peek(scopeContainer::deleteScopeMapping).map(ModelToRepresentation::toBriefRepresentation).collect(Collectors.toList());
    } else {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = scopedClient.getRole(role.getName());
            if (roleModel == null) {
                throw new NotFoundException("Role not found");
            }
            scopeContainer.deleteScopeMapping(roleModel);
        }
    }
    adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).representation(roles).success();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes)

Aggregations

ModelToRepresentation (org.keycloak.models.utils.ModelToRepresentation)12 Path (javax.ws.rs.Path)9 GET (javax.ws.rs.GET)8 Produces (javax.ws.rs.Produces)8 NoCache (org.jboss.resteasy.annotations.cache.NoCache)8 RoleModel (org.keycloak.models.RoleModel)8 NotFoundException (javax.ws.rs.NotFoundException)6 Collectors (java.util.stream.Collectors)5 Stream (java.util.stream.Stream)5 Consumes (javax.ws.rs.Consumes)5 DELETE (javax.ws.rs.DELETE)5 OperationType (org.keycloak.events.admin.OperationType)5 KeycloakSession (org.keycloak.models.KeycloakSession)5 RealmModel (org.keycloak.models.RealmModel)5 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)5 ResourceType (org.keycloak.events.admin.ResourceType)4 Date (java.util.Date)3 List (java.util.List)3 Map (java.util.Map)3 Predicate (java.util.function.Predicate)3