Search in sources :

Example 41 with ModelException

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

the class UserStorageProvidersTestUtils method getStorageProvider.

public static UserStorageProvider getStorageProvider(KeycloakSession session, RealmModel realm, String componentId) {
    ComponentModel model = realm.getComponent(componentId);
    if (model == null)
        return null;
    UserStorageProviderModel storageModel = new UserStorageProviderModel(model);
    UserStorageProviderFactory factory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, model.getProviderId());
    if (factory == null) {
        throw new ModelException("Could not find UserStorageProviderFactory for: " + model.getProviderId());
    }
    return getStorageProviderInstance(session, storageModel, factory);
}
Also used : UserStorageProvider(org.keycloak.storage.UserStorageProvider) ModelException(org.keycloak.models.ModelException) UserStorageProviderFactory(org.keycloak.storage.UserStorageProviderFactory) ComponentModel(org.keycloak.component.ComponentModel) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel)

Example 42 with ModelException

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

the class ClientRoleMappingsResource method addClientRoleMapping.

/**
 * Add client-level roles to the user role mapping
 *
 * @param roles
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void addClientRoleMapping(List<RoleRepresentation> roles) {
    managePermission.require();
    try {
        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);
            user.grantRole(roleModel);
        }
    } catch (ModelException | ReadOnlyException me) {
        logger.warn(me.getMessage(), me);
        throw new ErrorResponseException("invalid_request", "Could not add user role mappings!", Response.Status.BAD_REQUEST);
    }
    adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo).representation(roles).success();
}
Also used : 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) ReadOnlyException(org.keycloak.storage.ReadOnlyException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 43 with ModelException

use of org.keycloak.models.ModelException 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 44 with ModelException

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

the class RealmAdminResource method updateRealm.

/**
 * Update the top-level information of the realm
 *
 * Any user, roles or client information in the representation
 * will be ignored.  This will only update top-level attributes of the realm.
 *
 * @param rep
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateRealm(final RealmRepresentation rep) {
    auth.realm().requireManageRealm();
    logger.debug("updating realm: " + realm.getName());
    if (Config.getAdminRealm().equals(realm.getName()) && (rep.getRealm() != null && !rep.getRealm().equals(Config.getAdminRealm()))) {
        return ErrorResponse.error("Can't rename master realm", Status.BAD_REQUEST);
    }
    ReservedCharValidator.validate(rep.getRealm());
    ReservedCharValidator.validateLocales(rep.getSupportedLocales());
    try {
        if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getPrivateKey() != null && rep.getPublicKey() != null)) {
            try {
                KeyPairVerifier.verify(rep.getPrivateKey(), rep.getPublicKey());
            } catch (VerificationException e) {
                return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
            }
        }
        if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getCertificate() != null)) {
            try {
                X509Certificate cert = PemUtils.decodeCertificate(rep.getCertificate());
                if (cert == null) {
                    return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
                }
            } catch (Exception e) {
                return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
            }
        }
        boolean wasDuplicateEmailsAllowed = realm.isDuplicateEmailsAllowed();
        RepresentationToModel.updateRealm(rep, realm, session);
        // Refresh periodic sync tasks for configured federationProviders
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        realm.getUserStorageProvidersStream().forEachOrdered(fedProvider -> usersSyncManager.notifyToRefreshPeriodicSync(session, realm, fedProvider, false));
        // This populates the map in DefaultKeycloakContext to be used when treating the event
        session.getContext().getUri();
        adminEvent.operation(OperationType.UPDATE).representation(StripSecretsUtils.strip(rep)).success();
        if (rep.isDuplicateEmailsAllowed() != null && rep.isDuplicateEmailsAllowed() != wasDuplicateEmailsAllowed) {
            UserCache cache = session.getProvider(UserCache.class);
            if (cache != null)
                cache.clear();
        }
        return Response.noContent().build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Realm with same name exists");
    } catch (ModelException e) {
        return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return ErrorResponse.error("Failed to update realm", Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) ModelException(org.keycloak.models.ModelException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) VerificationException(org.keycloak.common.VerificationException) UserCache(org.keycloak.models.cache.UserCache) X509Certificate(java.security.cert.X509Certificate) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) BadRequestException(javax.ws.rs.BadRequestException) ParseException(java.text.ParseException) VerificationException(org.keycloak.common.VerificationException) NotFoundException(javax.ws.rs.NotFoundException) ModelException(org.keycloak.models.ModelException) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 45 with ModelException

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

the class LDAPGroupMapperTest method test02_readOnlyGroupMappings.

protected void test02_readOnlyGroupMappings(boolean importEnabled) {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "groupsMapper");
        LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.MODE, LDAPGroupMapperMode.READ_ONLY.toString());
        appRealm.updateComponent(mapperModel);
        GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
        GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
        // Add some group mappings directly into LDAP
        GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), appRealm);
        LDAPObject maryLdap = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "marykeycloak");
        groupMapper.addGroupMappingInLDAP(appRealm, group1, maryLdap);
        groupMapper.addGroupMappingInLDAP(appRealm, group11, maryLdap);
    });
    if (importEnabled) {
        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();
            UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
            GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
            GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
            GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
            // Add some group mapping to model
            mary.joinGroup(group12);
            // Assert that mary has both LDAP and DB mapped groups
            Set<GroupModel> maryGroups = mary.getGroupsStream().collect(Collectors.toSet());
            Assert.assertEquals(5, maryGroups.size());
            Assert.assertTrue(maryGroups.contains(group1));
            Assert.assertTrue(maryGroups.contains(group11));
            Assert.assertTrue(maryGroups.contains(group12));
            long groupCount = mary.getGroupsCount();
            Assert.assertEquals(5, groupCount);
            Assert.assertEquals(5, mary.getGroupsStream("gr", 0, 10).count());
            Assert.assertEquals(4, mary.getGroupsStream("gr", 1, 10).count());
            Assert.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count());
            Assert.assertEquals(2, mary.getGroupsStream("12", 0, 10).count());
        });
    } else {
        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();
            UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
            GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
            // as it is not allowed to update group mappings in LDAP nor in the DB
            try {
                mary.joinGroup(group12);
                Assert.fail("Not expected to successfully add group12 in no-import mode and READ_ONLY mode of the group mapper");
            } catch (ModelException me) {
            // Ignore
            }
        });
        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();
            UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
            GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
            GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
            GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
            // Assert that mary has both LDAP and DB mapped groups
            Set<GroupModel> maryGroups = mary.getGroupsStream().collect(Collectors.toSet());
            Assert.assertEquals(4, maryGroups.size());
            Assert.assertTrue(maryGroups.contains(group1));
            Assert.assertTrue(maryGroups.contains(group11));
            Assert.assertFalse(maryGroups.contains(group12));
            long groupCount = mary.getGroupsCount();
            Assert.assertEquals(4, groupCount);
            Assert.assertEquals(4, mary.getGroupsStream("gr", 0, 10).count());
            Assert.assertEquals(3, mary.getGroupsStream("gr", 1, 10).count());
            Assert.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count());
            Assert.assertEquals(1, mary.getGroupsStream("12", 0, 10).count());
        });
    }
    // Assert that access through DB will have just DB mapped groups
    if (importEnabled) {
        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();
            GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
            GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
            GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
            UserModel maryDB = session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak");
            Set<GroupModel> maryDBGroups = maryDB.getGroupsStream().collect(Collectors.toSet());
            Assert.assertFalse(maryDBGroups.contains(group1));
            Assert.assertFalse(maryDBGroups.contains(group11));
            Assert.assertTrue(maryDBGroups.contains(group12));
            Assert.assertEquals(3, maryDB.getGroupsStream("Gr", 0, 10).count());
            Assert.assertEquals(2, maryDB.getGroupsStream("Gr", 1, 10).count());
            Assert.assertEquals(1, maryDB.getGroupsStream("Gr", 0, 1).count());
            Assert.assertEquals(2, maryDB.getGroupsStream("12", 0, 10).count());
            long dbGroupCount = maryDB.getGroupsCount();
            Assert.assertEquals(3, dbGroupCount);
            // Test the group mapping available for group12
            List<UserModel> group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10).collect(Collectors.toList());
            Assert.assertEquals(1, group12Members.size());
            Assert.assertEquals("marykeycloak", group12Members.get(0).getUsername());
            UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
            mary.leaveGroup(group12);
        });
    } else {
        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();
            GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
            // Test the group mapping NOT available for group12
            Stream<UserModel> group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10);
            Assert.assertEquals(0, group12Members.count());
        });
    }
    // Check through userProvider
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
        GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
        GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
        UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
        UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
        ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "groupsMapper");
        GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), appRealm);
        LDAPObject maryLdap = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "marykeycloak");
        List<UserModel> group1Members = session.users().getGroupMembersStream(appRealm, group1, 0, 10).collect(Collectors.toList());
        List<UserModel> group11Members = session.users().getGroupMembersStream(appRealm, group11, 0, 10).collect(Collectors.toList());
        Assert.assertEquals(1, group1Members.size());
        Assert.assertEquals("marykeycloak", group1Members.get(0).getUsername());
        Assert.assertEquals(1, group11Members.size());
        Assert.assertEquals("marykeycloak", group11Members.get(0).getUsername());
        try {
            mary.leaveGroup(group1);
            Assert.fail("It wasn't expected to successfully delete LDAP group mappings in READ_ONLY mode");
        } catch (ModelException expected) {
        }
        // Delete group mappings directly in LDAP
        LDAPObject ldapGroup = groupMapper.loadLDAPGroupByName("group1");
        groupMapper.deleteGroupMappingInLDAP(maryLdap, ldapGroup);
        ldapGroup = groupMapper.loadLDAPGroupByName("group11");
        groupMapper.deleteGroupMappingInLDAP(maryLdap, ldapGroup);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ModelException(org.keycloak.models.ModelException) ComponentModel(org.keycloak.component.ComponentModel) GroupModel(org.keycloak.models.GroupModel) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) GroupLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper)

Aggregations

ModelException (org.keycloak.models.ModelException)74 RealmModel (org.keycloak.models.RealmModel)20 NamingException (javax.naming.NamingException)13 UserModel (org.keycloak.models.UserModel)13 ClientModel (org.keycloak.models.ClientModel)11 ComponentModel (org.keycloak.component.ComponentModel)10 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)10 IOException (java.io.IOException)9 Consumes (javax.ws.rs.Consumes)9 NotFoundException (javax.ws.rs.NotFoundException)8 BasicAttribute (javax.naming.directory.BasicAttribute)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 RoleModel (org.keycloak.models.RoleModel)7 ErrorResponseException (org.keycloak.services.ErrorResponseException)7 ReadOnlyException (org.keycloak.storage.ReadOnlyException)7 POST (javax.ws.rs.POST)6 Path (javax.ws.rs.Path)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 AttributeInUseException (javax.naming.directory.AttributeInUseException)5