Search in sources :

Example 36 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class ClientResource method getServiceAccountUser.

/**
 * Get a user dedicated to the service account
 *
 * @return
 */
@Path("service-account-user")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public UserRepresentation getServiceAccountUser() {
    auth.clients().requireView(client);
    UserModel user = session.users().getServiceAccount(client);
    if (user == null) {
        if (client.isServiceAccountsEnabled()) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(client);
            user = session.users().getServiceAccount(client);
        } else {
            throw new BadRequestException("Service account not enabled for the client '" + client.getClientId() + "'");
        }
    }
    return ModelToRepresentation.toRepresentation(session, realm, user);
}
Also used : UserModel(org.keycloak.models.UserModel) ClientManager(org.keycloak.services.managers.ClientManager) BadRequestException(org.jboss.resteasy.spi.BadRequestException) RealmManager(org.keycloak.services.managers.RealmManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 37 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class RealmAdminResource method updateRealmEventsConfig.

/**
 * Update the events provider
 *
 * Change the events provider and/or its configuration
 *
 * @param rep
 */
@PUT
@Path("events/config")
@Consumes(MediaType.APPLICATION_JSON)
public void updateRealmEventsConfig(final RealmEventsConfigRepresentation rep) {
    auth.realm().requireManageEvents();
    logger.debug("updating realm events config: " + realm.getName());
    new RealmManager(session).updateRealmEventsConfig(rep, realm);
    adminEvent.operation(OperationType.UPDATE).resource(ResourceType.REALM).realm(realm).resourcePath(session.getContext().getUri()).representation(rep).refreshRealmEventsConfig(session).success();
}
Also used : RealmManager(org.keycloak.services.managers.RealmManager) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 38 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class FederatedStorageExportImportTest method testDir.

@Test
public void testDir() {
    ComponentExportImportTest.clearExportImportProperties(testingClient);
    final String userId = "f:1:path";
    testingClient.server().run(session -> {
        RealmModel realm = new RealmManager(session).createRealm(REALM_NAME);
        RoleModel role = realm.addRole("test-role");
        GroupModel group = realm.createGroup("test-group");
        List<String> attrValues = new LinkedList<>();
        attrValues.add("1");
        attrValues.add("2");
        session.userFederatedStorage().setSingleAttribute(realm, userId, "single1", "value1");
        session.userFederatedStorage().setAttribute(realm, userId, "list1", attrValues);
        session.userFederatedStorage().addRequiredAction(realm, userId, "UPDATE_PASSWORD");
        PasswordCredentialModel credential = FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).encodedCredential("password", realm.getPasswordPolicy().getHashIterations());
        session.userFederatedStorage().createCredential(realm, userId, credential);
        session.userFederatedStorage().grantRole(realm, userId, role);
        session.userFederatedStorage().joinGroup(realm, userId, group);
        session.userFederatedStorage().setNotBeforeForUser(realm, userId, 50);
    });
    final String realmId = testRealmResource().toRepresentation().getId();
    final String groupId = testRealmResource().getGroupByPath("/test-group").getId();
    final String exportDirAbsolutePath = this.exportDirAbsolutePath;
    testingClient.server().run(session -> {
        ExportImportConfig.setProvider(DirExportProviderFactory.PROVIDER_ID);
        ExportImportConfig.setDir(exportDirAbsolutePath);
        ExportImportConfig.setRealmName(REALM_NAME);
        ExportImportConfig.setAction(ExportImportConfig.ACTION_EXPORT);
        new ExportImportManager(session).runExport();
        session.realms().removeRealm(realmId);
    });
    testingClient.server().run(session -> {
        Assert.assertNull(session.realms().getRealmByName(REALM_NAME));
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);
        new ExportImportManager(session).runImport();
    });
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(REALM_NAME);
        Assert.assertNotNull(realm);
        RoleModel role = realm.getRole("test-role");
        GroupModel group = realm.getGroupById(groupId);
        Assert.assertEquals(1, session.userFederatedStorage().getStoredUsersCount(realm));
        MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, userId);
        Assert.assertEquals(3, attributes.size());
        Assert.assertEquals("value1", attributes.getFirst("single1"));
        Assert.assertTrue(attributes.getList("list1").contains("1"));
        Assert.assertTrue(attributes.getList("list1").contains("2"));
        Assert.assertTrue(session.userFederatedStorage().getRequiredActionsStream(realm, userId).collect(Collectors.toSet()).contains("UPDATE_PASSWORD"));
        Assert.assertTrue(session.userFederatedStorage().getRoleMappingsStream(realm, userId).collect(Collectors.toSet()).contains(role));
        Assert.assertTrue(session.userFederatedStorage().getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group));
        Assert.assertEquals(50, session.userFederatedStorage().getNotBeforeOfUser(realm, userId));
        List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentialsStream(realm, userId).collect(Collectors.toList());
        Assert.assertEquals(1, creds.size());
        Assert.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).verify("password", PasswordCredentialModel.createFromCredentialModel(creds.get(0))));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) GroupModel(org.keycloak.models.GroupModel) ExportImportManager(org.keycloak.exportimport.ExportImportManager) RoleModel(org.keycloak.models.RoleModel) RealmManager(org.keycloak.services.managers.RealmManager) LinkedList(java.util.LinkedList) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 39 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class UserModelTest method testServiceAccountLink.

@Test
@ModelTest
public void testServiceAccountLink(KeycloakSession session) throws Exception {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesServiceLink1) -> {
        KeycloakSession currentSession = sesServiceLink1;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        ClientModel client = realm.addClient("foo");
        UserModel user1 = currentSession.users().addUser(realm, "user1");
        user1.setFirstName("John");
        user1.setLastName("Doe");
        UserModel user2 = currentSession.users().addUser(realm, "user2");
        user2.setFirstName("John");
        user2.setLastName("Doe");
        // Search
        Assert.assertThat(currentSession.users().getServiceAccount(client), nullValue());
        List<UserModel> users = currentSession.users().searchForUserStream(realm, "John Doe").collect(Collectors.toList());
        Assert.assertThat(users, hasSize(2));
        Assert.assertThat(users, containsInAnyOrder(user1, user2));
        // Link service account
        user1.setServiceAccountClientLink(client.getId());
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesServiceLink2) -> {
        KeycloakSession currentSession = sesServiceLink2;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
        UserModel user2 = currentSession.users().getUserByUsername(realm, "user2");
        // Search and assert service account user not found
        ClientModel client = realm.getClientByClientId("foo");
        UserModel searched = currentSession.users().getServiceAccount(client);
        Assert.assertThat(searched, equalTo(user1));
        List<UserModel> users = currentSession.users().searchForUserStream(realm, "John Doe").collect(Collectors.toList());
        Assert.assertThat(users, hasSize(1));
        Assert.assertThat(users, contains(user2));
        users = currentSession.users().getUsersStream(realm, false).collect(Collectors.toList());
        Assert.assertThat(users, hasSize(1));
        Assert.assertThat(users, contains(user2));
        users = currentSession.users().getUsersStream(realm, true).collect(Collectors.toList());
        Assert.assertThat(users, hasSize(2));
        Assert.assertThat(users, containsInAnyOrder(user1, user2));
        Assert.assertThat(currentSession.users().getUsersCount(realm, true), equalTo(2));
        Assert.assertThat(currentSession.users().getUsersCount(realm, false), equalTo(1));
        // Remove client
        RealmManager realmMgr = new RealmManager(currentSession);
        ClientManager clientMgr = new ClientManager(realmMgr);
        clientMgr.removeClient(realm, client);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesServiceLink3) -> {
        KeycloakSession currentSession = sesServiceLink3;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        // Assert service account removed as well
        Assert.assertThat(currentSession.users().getUserByUsername(realm, "user1"), nullValue());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) ClientManager(org.keycloak.services.managers.ClientManager) RealmManager(org.keycloak.services.managers.RealmManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 40 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class AuthenticationSessionProviderTest method testOnRealmRemoved.

@Test
@ModelTest
public void testOnRealmRemoved(KeycloakSession session) {
    AtomicReference<String> authSessionID = new AtomicReference<>();
    AtomicReference<String> authSessionID2 = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
        KeycloakSession currentSession = sesRealmRemoved1;
        RealmModel realm = currentSession.realms().getRealm("test");
        RealmModel fooRealm = currentSession.realms().createRealm("foo-realm");
        fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
        fooRealm.addClient("foo-client");
        authSessionID.set(currentSession.authenticationSessions().createRootAuthenticationSession(realm).getId());
        authSessionID2.set(currentSession.authenticationSessions().createRootAuthenticationSession(fooRealm).getId());
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved2) -> {
        KeycloakSession currentSession = sesRealmRemoved2;
        new RealmManager(currentSession).removeRealm(currentSession.realms().getRealmByName("foo-realm"));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved3) -> {
        KeycloakSession currentSession = sesRealmRemoved3;
        RealmModel realm = currentSession.realms().getRealm("test");
        RootAuthenticationSessionModel authSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
        assertThat(authSession, notNullValue());
        assertThat(currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID2.get()), nullValue());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

RealmManager (org.keycloak.services.managers.RealmManager)47 RealmModel (org.keycloak.models.RealmModel)34 Test (org.junit.Test)19 UserModel (org.keycloak.models.UserModel)17 KeycloakSession (org.keycloak.models.KeycloakSession)16 ClientModel (org.keycloak.models.ClientModel)13 ClientManager (org.keycloak.services.managers.ClientManager)11 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)8 Path (javax.ws.rs.Path)6 UserSessionModel (org.keycloak.models.UserSessionModel)6 UserManager (org.keycloak.models.UserManager)5 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)4 LinkedList (java.util.LinkedList)3 GET (javax.ws.rs.GET)3 NotFoundException (javax.ws.rs.NotFoundException)3 Produces (javax.ws.rs.Produces)3 UserConsentModel (org.keycloak.models.UserConsentModel)3 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)3