Search in sources :

Example 11 with KeycloakSessionFactory

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

the class IdentityProviderResource method getMapperTypes.

/**
 * Get mapper types for identity provider
 */
@GET
@Path("mapper-types")
@NoCache
public Map<String, IdentityProviderMapperTypeRepresentation> getMapperTypes() {
    this.auth.realm().requireViewIdentityProviders();
    if (identityProviderModel == null) {
        throw new javax.ws.rs.NotFoundException();
    }
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    return sessionFactory.getProviderFactoriesStream(IdentityProviderMapper.class).map(IdentityProviderMapper.class::cast).map(mapper -> Arrays.stream(mapper.getCompatibleProviders()).filter(type -> Objects.equals(IdentityProviderMapper.ANY_PROVIDER, type) || Objects.equals(identityProviderModel.getProviderId(), type)).map(type -> {
        IdentityProviderMapperTypeRepresentation rep = new IdentityProviderMapperTypeRepresentation();
        rep.setId(mapper.getId());
        rep.setCategory(mapper.getDisplayCategory());
        rep.setName(mapper.getDisplayType());
        rep.setHelpText(mapper.getHelpText());
        rep.setProperties(mapper.getConfigProperties().stream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList()));
        return rep;
    }).findFirst().orElse(null)).filter(Objects::nonNull).collect(Collectors.toMap(IdentityProviderMapperTypeRepresentation::getId, Function.identity()));
}
Also used : OperationType(org.keycloak.events.admin.OperationType) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) PathParam(javax.ws.rs.PathParam) Arrays(java.util.Arrays) ResourceType(org.keycloak.events.admin.ResourceType) IdentityProviderFactory(org.keycloak.broker.provider.IdentityProviderFactory) Produces(javax.ws.rs.Produces) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Path(javax.ws.rs.Path) IdentityProviderMapperTypeRepresentation(org.keycloak.representations.idm.IdentityProviderMapperTypeRepresentation) Function(java.util.function.Function) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) MediaType(javax.ws.rs.core.MediaType) UserModel(org.keycloak.models.UserModel) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) IdentityProviderMapperRepresentation(org.keycloak.representations.idm.IdentityProviderMapperRepresentation) AdminPermissionManagement(org.keycloak.services.resources.admin.permissions.AdminPermissionManagement) StripSecretsUtils(org.keycloak.models.utils.StripSecretsUtils) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) DELETE(javax.ws.rs.DELETE) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) AdminPermissions(org.keycloak.services.resources.admin.permissions.AdminPermissions) RealmModel(org.keycloak.models.RealmModel) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) Streams(com.google.common.collect.Streams) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) ManagementPermissionReference(org.keycloak.representations.idm.ManagementPermissionReference) Objects(java.util.Objects) SocialIdentityProvider(org.keycloak.broker.social.SocialIdentityProvider) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) Stream(java.util.stream.Stream) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) PUT(javax.ws.rs.PUT) ErrorResponse(org.keycloak.services.ErrorResponse) IdentityProviderMapperTypeRepresentation(org.keycloak.representations.idm.IdentityProviderMapperTypeRepresentation) NotFoundException(javax.ws.rs.NotFoundException) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 12 with KeycloakSessionFactory

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

the class LDAPSyncTest method test09MembershipUsingDifferentAttributes.

// KEYCLOAK-14696
@Test
public void test09MembershipUsingDifferentAttributes() throws Exception {
    final Map<String, String> previousConf = testingClient.server().fetch(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        // Remove all users from model
        session.userLocalStorage().getUsersStream(ctx.getRealm(), true).peek(user -> System.out.println("trying to delete user: " + user.getUsername())).collect(Collectors.toList()).forEach(user -> {
            UserCache userCache = session.userCache();
            if (userCache != null) {
                userCache.evict(ctx.getRealm(), user);
            }
            session.userLocalStorage().removeUser(ctx.getRealm(), user);
        });
        Map<String, String> orig = new HashMap<>();
        orig.put(LDAPConstants.RDN_LDAP_ATTRIBUTE, ctx.getLdapModel().getConfig().getFirst(LDAPConstants.RDN_LDAP_ATTRIBUTE));
        orig.put(LDAPConstants.USERS_DN, ctx.getLdapModel().getConfig().getFirst(LDAPConstants.USERS_DN));
        orig.put(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, ctx.getLdapModel().getConfig().getFirst(LDAPConstants.USERNAME_LDAP_ATTRIBUTE));
        // create an OU and this test will work below it, set RDN to CN and username to uid/samaccountname
        LDAPTestUtils.addLdapOU(ctx.getLdapProvider(), "KC14696");
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERS_DN, "ou=KC14696," + orig.get(LDAPConstants.USERS_DN));
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.RDN_LDAP_ATTRIBUTE, LDAPConstants.CN);
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, ctx.getLdapProvider().getLdapIdentityStore().getConfig().isActiveDirectory() ? LDAPConstants.SAM_ACCOUNT_NAME : LDAPConstants.UID);
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "username");
        mapperModel.getConfig().putSingle(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, ctx.getLdapProvider().getLdapIdentityStore().getConfig().isActiveDirectory() ? LDAPConstants.SAM_ACCOUNT_NAME : LDAPConstants.UID);
        ctx.getRealm().updateComponent(mapperModel);
        LDAPTestUtils.addUserAttributeMapper(appRealm, LDAPTestUtils.getLdapProviderModel(appRealm), "cnMapper", "firstName", LDAPConstants.CN);
        return orig;
    }, Map.class);
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        // create a user8 inside the usersDn
        LDAPObject user8 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "user8", "User8FN", "User8LN", "user8@email.org", "user8street", "126");
        // create a sample ou inside usersDn
        LDAPTestUtils.addLdapOU(ctx.getLdapProvider(), "sample-org");
        // create a user below the sample org with the same common-name but different username
        String usersDn = ctx.getLdapModel().get(LDAPConstants.USERS_DN);
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERS_DN, "ou=sample-org," + usersDn);
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "user8bis", "User8FN", "User8LN", "user8bis@email.org", "user8street", "126");
        // get back to parent usersDn
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.USERS_DN, usersDn);
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        // create a group with user8 as a member
        String descriptionAttrName = LDAPTestUtils.getGroupDescriptionLDAPAttrName(ctx.getLdapProvider());
        LDAPObject user8Group = LDAPTestUtils.createLDAPGroup(session, appRealm, ctx.getLdapModel(), "user8group", descriptionAttrName, "user8group - description");
        LDAPUtils.addMember(ctx.getLdapProvider(), MembershipType.DN, LDAPConstants.MEMBER, "not-used", user8Group, user8);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
        Assert.assertEquals(2, syncResult.getAdded());
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        GroupModel user8Group = KeycloakModelUtils.findGroupByPath(appRealm, "/user8group");
        Assert.assertNotNull(user8Group);
        UserModel user8 = session.users().getUserByUsername(appRealm, "user8");
        Assert.assertNotNull(user8);
        UserModel user8Bis = session.users().getUserByUsername(appRealm, "user8bis");
        Assert.assertNotNull(user8Bis);
        Assert.assertTrue("User user8 contains the group", user8.getGroupsStream().collect(Collectors.toSet()).contains(user8Group));
        Assert.assertFalse("User user8bis does not contain the group", user8Bis.getGroupsStream().collect(Collectors.toSet()).contains(user8Group));
        List<String> members = session.users().getGroupMembersStream(appRealm, user8Group).map(u -> u.getUsername()).collect(Collectors.toList());
        Assert.assertEquals("Group contains only user8", members, Collections.singletonList("user8"));
    });
    // revert changes
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        session.users().removeImportedUsers(appRealm, ldapModelId);
        LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), appRealm, ctx.getLdapProvider().getLdapIdentityStore().getConfig(), "user8");
        LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), appRealm, ctx.getLdapProvider().getLdapIdentityStore().getConfig(), "user8bis");
        LDAPObject ou = new LDAPObject();
        ou.setDn(LDAPDn.fromString("ou=sample-org,ou=KC14696," + previousConf.get(LDAPConstants.USERS_DN)));
        ctx.getLdapProvider().getLdapIdentityStore().remove(ou);
        ou.setDn(LDAPDn.fromString("ou=KC14696," + previousConf.get(LDAPConstants.USERS_DN)));
        ctx.getLdapProvider().getLdapIdentityStore().remove(ou);
        for (Map.Entry<String, String> e : previousConf.entrySet()) {
            if (e.getValue() == null) {
                ctx.getLdapModel().getConfig().remove(e.getKey());
            } else {
                ctx.getLdapModel().getConfig().putSingle(e.getKey(), e.getValue());
            }
        }
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        ComponentModel cnMapper = LDAPTestUtils.getSubcomponentByName(ctx.getRealm(), ctx.getLdapModel(), "cnMapper");
        ctx.getRealm().removeComponent(cnMapper);
        ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "username");
        mapperModel.getConfig().putSingle(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, ctx.getLdapProvider().getLdapIdentityStore().getConfig().getUsernameLdapAttribute());
        ctx.getRealm().updateComponent(mapperModel);
    });
}
Also used : MethodSorters(org.junit.runners.MethodSorters) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) HashMap(java.util.HashMap) SynchronizationResultRepresentation(org.keycloak.representations.idm.SynchronizationResultRepresentation) LDAPConstants(org.keycloak.models.LDAPConstants) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) UserModel(org.keycloak.models.UserModel) LDAPRule(org.keycloak.testsuite.util.LDAPRule) Map(java.util.Map) ComponentModel(org.keycloak.component.ComponentModel) GroupModel(org.keycloak.models.GroupModel) BadRequestException(javax.ws.rs.BadRequestException) ClassRule(org.junit.ClassRule) LDAPGroupMapperMode(org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode) LDAPDn(org.keycloak.storage.ldap.idm.model.LDAPDn) MembershipType(org.keycloak.storage.ldap.mappers.membership.MembershipType) WaitUtils(org.keycloak.testsuite.util.WaitUtils) RealmModel(org.keycloak.models.RealmModel) LDAPTestUtils(org.keycloak.testsuite.util.LDAPTestUtils) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) LDAPStorageProviderFactory(org.keycloak.storage.ldap.LDAPStorageProviderFactory) GroupLDAPStorageMapperFactory(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapperFactory) Collectors(java.util.stream.Collectors) GroupLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) UserProvider(org.keycloak.models.UserProvider) List(java.util.List) UserCache(org.keycloak.models.cache.UserCache) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) LDAPUtils(org.keycloak.storage.ldap.LDAPUtils) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) Assert(org.junit.Assert) FixMethodOrder(org.junit.FixMethodOrder) Collections(java.util.Collections) GroupMapperConfig(org.keycloak.storage.ldap.mappers.membership.group.GroupMapperConfig) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) HashMap(java.util.HashMap) GroupModel(org.keycloak.models.GroupModel) UserCache(org.keycloak.models.cache.UserCache) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ComponentModel(org.keycloak.component.ComponentModel) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 13 with KeycloakSessionFactory

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

the class LDAPSyncTest method test01LDAPSync.

// @Test
// public void test01runit() throws Exception {
// Thread.sleep(10000000);
// }
@Test
public void test01LDAPSync() {
    // wait a bit
    WaitUtils.pause(getLDAPRule().getSleepTime());
    // Sync 5 users from LDAP
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        SynchronizationResult syncResult = usersSyncManager.syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
        LDAPTestAsserts.assertSyncEquals(syncResult, 5, 0, 0, 0);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel testRealm = ctx.getRealm();
        UserProvider userProvider = session.userLocalStorage();
        // Assert users imported
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user1", "User1FN", "User1LN", "user1@email.org", "121");
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user2", "User2FN", "User2LN", "user2@email.org", "122");
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user3", "User3FN", "User3LN", "user3@email.org", "123");
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user4", "User4FN", "User4LN", "user4@email.org", "124");
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5@email.org", "125");
        // Assert lastSync time updated
        Assert.assertTrue(ctx.getLdapModel().getLastSync() > 0);
        testRealm.getUserStorageProvidersStream().forEachOrdered(persistentFedModel -> {
            if (LDAPStorageProviderFactory.PROVIDER_NAME.equals(persistentFedModel.getProviderId())) {
                Assert.assertTrue(persistentFedModel.getLastSync() > 0);
            } else {
                // Dummy provider has still 0
                Assert.assertEquals(0, persistentFedModel.getLastSync());
            }
        });
    });
    // wait a bit
    WaitUtils.pause(getLDAPRule().getSleepTime());
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel testRealm = ctx.getRealm();
        UserProvider userProvider = session.userLocalStorage();
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        // Add user to LDAP and update 'user5' in LDAP
        LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), testRealm, "user6", "User6FN", "User6LN", "user6@email.org", null, "126");
        LDAPObject ldapUser5 = ctx.getLdapProvider().loadLDAPUserByUsername(testRealm, "user5");
        // NOTE: Changing LDAP attributes directly here
        ldapUser5.setSingleAttribute(LDAPConstants.EMAIL, "user5Updated@email.org");
        ldapUser5.setSingleAttribute(LDAPConstants.POSTAL_CODE, "521");
        ctx.getLdapProvider().getLdapIdentityStore().update(ldapUser5);
        // Assert still old users in local provider
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5@email.org", "125");
        Assert.assertNull(userProvider.getUserByUsername(testRealm, "user6"));
        // Trigger partial sync
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        SynchronizationResult syncResult = usersSyncManager.syncChangedUsers(sessionFactory, "test", ctx.getLdapModel());
        LDAPTestAsserts.assertSyncEquals(syncResult, 1, 1, 0, 0);
    });
    testingClient.server().run(session -> {
        RealmModel testRealm = session.realms().getRealm("test");
        UserProvider userProvider = session.userLocalStorage();
        // Assert users updated in local provider
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5updated@email.org", "521");
        LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user6", "User6FN", "User6LN", "user6@email.org", "126");
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) UserProvider(org.keycloak.models.UserProvider) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) Test(org.junit.Test)

Example 14 with KeycloakSessionFactory

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

the class LDAPSyncTest method test04SameUUIDAndUsernameSync.

// KEYCLOAK-1571
@Test
public void test04SameUUIDAndUsernameSync() {
    String origUuidAttrName = testingClient.server().fetch(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        // Remove all users from model
        session.userLocalStorage().getUsersStream(ctx.getRealm(), true).collect(Collectors.toList()).forEach(user -> session.userLocalStorage().removeUser(ctx.getRealm(), user));
        // Change name of UUID attribute to same like usernameAttribute
        String uidAttrName = ctx.getLdapProvider().getLdapIdentityStore().getConfig().getUsernameLdapAttribute();
        String origUuidAttrNamee = ctx.getLdapModel().get(LDAPConstants.UUID_LDAP_ATTRIBUTE);
        ctx.getLdapModel().put(LDAPConstants.UUID_LDAP_ATTRIBUTE, uidAttrName);
        // Need to change this due to ApacheDS pagination bug (For other LDAP servers, pagination works fine) TODO: Remove once ApacheDS upgraded and pagination is fixed
        ctx.getLdapModel().put(LDAPConstants.BATCH_SIZE_FOR_SYNC, "10");
        ctx.getRealm().updateComponent(ctx.getLdapModel());
        return origUuidAttrNamee;
    }, String.class);
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
        Assert.assertEquals(0, syncResult.getFailed());
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        // Assert users imported with correct LDAP_ID
        LDAPTestAsserts.assertUserImported(session.users(), ctx.getRealm(), "user1", "User1FN", "User1LN", "user1@email.org", "121");
        LDAPTestAsserts.assertUserImported(session.users(), ctx.getRealm(), "user2", "User2FN", "User2LN", "user2@email.org", "122");
        UserModel user1 = session.users().getUserByUsername(ctx.getRealm(), "user1");
        Assert.assertEquals("user1", user1.getFirstAttribute(LDAPConstants.LDAP_ID));
    });
    // Revert config changes
    ComponentRepresentation ldapRep = testRealm().components().component(ldapModelId).toRepresentation();
    ldapRep.getConfig().putSingle(LDAPConstants.UUID_LDAP_ATTRIBUTE, origUuidAttrName);
    testRealm().components().component(ldapModelId).update(ldapRep);
}
Also used : UserModel(org.keycloak.models.UserModel) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) Test(org.junit.Test)

Example 15 with KeycloakSessionFactory

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

the class LDAPSyncTest method test03LDAPSyncWhenUsernameChanged.

@Test
public void test03LDAPSyncWhenUsernameChanged() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        // Add user to LDAP
        LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "beckybecks", "Becky", "Becks", "becky-becks@email.org", null, "123");
        SynchronizationResult syncResult = new UserStorageSyncManager().syncAllUsers(sessionFactory, "test", ctx.getLdapModel());
        Assert.assertEquals(0, syncResult.getFailed());
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel testRealm = ctx.getRealm();
        UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
        // Update user 'beckybecks' in LDAP
        LDAPObject ldapUser = ctx.getLdapProvider().loadLDAPUserByUsername(testRealm, "beckybecks");
        // NOTE: Changing LDAP Username directly here
        String userNameLdapAttributeName = ctx.getLdapProvider().getLdapIdentityStore().getConfig().getUsernameLdapAttribute();
        ldapUser.setSingleAttribute(userNameLdapAttributeName, "beckyupdated");
        ldapUser.setSingleAttribute(LDAPConstants.EMAIL, "becky-updated@email.org");
        ctx.getLdapProvider().getLdapIdentityStore().update(ldapUser);
        // Assert still old users in local provider
        LDAPTestAsserts.assertUserImported(session.userLocalStorage(), testRealm, "beckybecks", "Becky", "Becks", "becky-becks@email.org", "123");
        // Trigger partial sync
        KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
        SynchronizationResult syncResult = usersSyncManager.syncChangedUsers(sessionFactory, "test", ctx.getLdapModel());
        Assert.assertEquals(0, syncResult.getFailed());
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel testRealm = session.realms().getRealm("test");
        UserProvider userProvider = session.userLocalStorage();
        // Assert users updated in local provider
        LDAPTestAsserts.assertUserImported(session.users(), testRealm, "beckyupdated", "Becky", "Becks", "becky-updated@email.org", "123");
        UserModel updatedLocalUser = userProvider.getUserByUsername(testRealm, "beckyupdated");
        LDAPObject ldapUser = ctx.getLdapProvider().loadLDAPUserByUsername(testRealm, "beckyupdated");
        // Assert old user 'beckybecks' does not exists locally
        Assert.assertNull(userProvider.getUserByUsername(testRealm, "beckybecks"));
        // Assert UUID didn't change
        Assert.assertEquals(updatedLocalUser.getAttributeStream(LDAPConstants.LDAP_ID).findFirst().get(), ldapUser.getUuid());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) UserProvider(org.keycloak.models.UserProvider) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) Test(org.junit.Test)

Aggregations

KeycloakSessionFactory (org.keycloak.models.KeycloakSessionFactory)33 KeycloakSession (org.keycloak.models.KeycloakSession)11 RealmModel (org.keycloak.models.RealmModel)11 Test (org.junit.Test)10 UserModel (org.keycloak.models.UserModel)9 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)9 UserStorageSyncManager (org.keycloak.services.managers.UserStorageSyncManager)8 ComponentModel (org.keycloak.component.ComponentModel)7 IdentityProviderMapper (org.keycloak.broker.provider.IdentityProviderMapper)5 ClusterProvider (org.keycloak.cluster.ClusterProvider)5 FederatedIdentityModel (org.keycloak.models.FederatedIdentityModel)5 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)5 HashMap (java.util.HashMap)4 Logger (org.jboss.logging.Logger)4 KeycloakModelUtils (org.keycloak.models.utils.KeycloakModelUtils)4 UserStorageProviderModel (org.keycloak.storage.UserStorageProviderModel)4 Arrays (java.util.Arrays)3 LinkedList (java.util.LinkedList)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 Function (java.util.function.Function)3