Search in sources :

Example 6 with ClientManager

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

the class ClientResource method updateClientFromRep.

private void updateClientFromRep(ClientRepresentation rep, ClientModel client, KeycloakSession session) throws ModelDuplicateException {
    UserModel serviceAccount = this.session.users().getServiceAccount(client);
    if (TRUE.equals(rep.isServiceAccountsEnabled())) {
        if (serviceAccount == null) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(client);
        }
    } else {
        if (serviceAccount != null) {
            new UserManager(session).removeUser(realm, serviceAccount);
        }
    }
    if (rep.getClientId() != null && !rep.getClientId().equals(client.getClientId())) {
        new ClientManager(new RealmManager(session)).clientIdChanged(client, rep);
    }
    if (rep.isFullScopeAllowed() != null && rep.isFullScopeAllowed() != client.isFullScopeAllowed()) {
        auth.clients().requireManage(client);
    }
    if ((rep.isBearerOnly() != null && rep.isBearerOnly()) || (rep.isPublicClient() != null && rep.isPublicClient())) {
        rep.setAuthorizationServicesEnabled(false);
    }
    RepresentationToModel.updateClient(rep, client);
    RepresentationToModel.updateClientProtocolMappers(rep, client);
    updateAuthorizationSettings(rep);
}
Also used : UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) ClientManager(org.keycloak.services.managers.ClientManager) RealmManager(org.keycloak.services.managers.RealmManager)

Example 7 with ClientManager

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

the class ClientsResource method createClient.

/**
 * Create a new client
 *
 * Client's client_id must be unique!
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createClient(final ClientRepresentation rep) {
    auth.clients().requireManage();
    try {
        session.clientPolicy().triggerOnEvent(new AdminClientRegisterContext(rep, auth.adminAuth()));
        ClientModel clientModel = ClientManager.createClient(session, realm, rep);
        if (TRUE.equals(rep.isServiceAccountsEnabled())) {
            UserModel serviceAccount = session.users().getServiceAccount(clientModel);
            if (serviceAccount == null) {
                new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
            }
        }
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), clientModel.getId()).representation(rep).success();
        if (Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION) && TRUE.equals(rep.getAuthorizationServicesEnabled())) {
            AuthorizationService authorizationService = getAuthorizationService(clientModel);
            authorizationService.enable(true);
            ResourceServerRepresentation authorizationSettings = rep.getAuthorizationSettings();
            if (authorizationSettings != null) {
                authorizationService.resourceServer().importSettings(authorizationSettings);
            }
        }
        ValidationUtil.validateClient(session, clientModel, true, r -> {
            session.getTransactionManager().setRollbackOnly();
            throw new ErrorResponseException(Errors.INVALID_INPUT, r.getAllLocalizedErrorsAsString(AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale())), Response.Status.BAD_REQUEST);
        });
        session.clientPolicy().triggerOnEvent(new AdminClientRegisteredContext(clientModel, auth.adminAuth()));
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(clientModel.getId()).build()).build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Client " + rep.getClientId() + " already exists");
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) AdminClientRegisteredContext(org.keycloak.services.clientpolicy.context.AdminClientRegisteredContext) AuthorizationService(org.keycloak.authorization.admin.AuthorizationService) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) ClientManager(org.keycloak.services.managers.ClientManager) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException) RealmManager(org.keycloak.services.managers.RealmManager) AdminClientRegisterContext(org.keycloak.services.clientpolicy.context.AdminClientRegisterContext) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 8 with ClientManager

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

the class UserSessionPersisterProviderTest method testOnClientRemoved.

@Test
public void testOnClientRemoved() {
    int started = Time.currentTime();
    AtomicReference<String> userSessionID = new AtomicReference<>();
    inComittedTransaction(session -> {
        RealmModel fooRealm = session.realms().createRealm("foo", "foo");
        fooRealm.setDefaultRole(session.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX));
        fooRealm.addClient("foo-app");
        fooRealm.addClient("bar-app");
        session.users().addUser(fooRealm, "user3");
        UserSessionModel userSession = session.sessions().createUserSession(fooRealm, session.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
        userSessionID.set(userSession.getId());
        createClientSession(session, realmId, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
        createClientSession(session, realmId, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
    });
    inComittedTransaction(session -> {
        RealmModel fooRealm = session.realms().getRealm("foo");
        // Persist offline session
        UserSessionModel userSession = session.sessions().getUserSession(fooRealm, userSessionID.get());
        persistUserSession(session, userSession, true);
    });
    inComittedTransaction(session -> {
        RealmManager realmMgr = new RealmManager(session);
        ClientManager clientMgr = new ClientManager(realmMgr);
        RealmModel fooRealm = realmMgr.getRealm("foo");
        // Assert session was persisted with both clientSessions
        UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
        assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app");
        // Remove foo-app client
        ClientModel client = fooRealm.getClientByClientId("foo-app");
        clientMgr.removeClient(fooRealm, client);
    });
    inComittedTransaction(session -> {
        RealmManager realmMgr = new RealmManager(session);
        ClientManager clientMgr = new ClientManager(realmMgr);
        RealmModel fooRealm = realmMgr.getRealm("foo");
        // Assert just one bar-app clientSession persisted now
        UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
        assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "bar-app");
        // Remove bar-app client
        ClientModel client = fooRealm.getClientByClientId("bar-app");
        clientMgr.removeClient(fooRealm, client);
    });
    inComittedTransaction(session -> {
        // Assert loading still works - last userSession is still there, but no clientSession on it
        loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        // Cleanup
        RealmManager realmMgr = new RealmManager(session);
        realmMgr.removeRealm(realmMgr.getRealm("foo"));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) ClientManager(org.keycloak.services.managers.ClientManager) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 9 with ClientManager

use of org.keycloak.services.managers.ClientManager 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 10 with ClientManager

use of org.keycloak.services.managers.ClientManager 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)

Aggregations

ClientManager (org.keycloak.services.managers.ClientManager)11 RealmManager (org.keycloak.services.managers.RealmManager)11 ClientModel (org.keycloak.models.ClientModel)7 UserModel (org.keycloak.models.UserModel)6 RealmModel (org.keycloak.models.RealmModel)5 Test (org.junit.Test)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 KeycloakSession (org.keycloak.models.KeycloakSession)3 UserSessionModel (org.keycloak.models.UserSessionModel)3 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)3 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)3 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)3 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 ModelDuplicateException (org.keycloak.models.ModelDuplicateException)2 UserManager (org.keycloak.models.UserManager)2 ErrorResponseException (org.keycloak.services.ErrorResponseException)2 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)2 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)2