Search in sources :

Example 1 with ClientManager

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

the class AdapterInstallationClientRegistrationProvider method get.

@GET
@Path("{clientId}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("clientId") String clientId) {
    event.event(EventType.CLIENT_INFO);
    ClientModel client = session.getContext().getRealm().getClientByClientId(clientId);
    auth.requireView(client, true);
    ClientManager clientManager = new ClientManager(new RealmManager(session));
    Object rep = clientManager.toInstallationRepresentation(session.getContext().getRealm(), client, session.getContext().getUri().getBaseUri());
    event.client(client.getClientId()).success();
    return Response.ok(rep).build();
}
Also used : ClientModel(org.keycloak.models.ClientModel) ClientManager(org.keycloak.services.managers.ClientManager) RealmManager(org.keycloak.services.managers.RealmManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 2 with ClientManager

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

the class AbstractClientRegistrationProvider method create.

public ClientRepresentation create(ClientRegistrationContext context) {
    ClientRepresentation client = context.getClient();
    event.event(EventType.CLIENT_REGISTER);
    RegistrationAuth registrationAuth = auth.requireCreate(context);
    try {
        RealmModel realm = session.getContext().getRealm();
        ClientModel clientModel = ClientManager.createClient(session, realm, client);
        if (client.getDefaultRoles() != null) {
            for (String name : client.getDefaultRoles()) {
                clientModel.addDefaultRole(name);
            }
        }
        if (clientModel.isServiceAccountsEnabled()) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
        }
        if (Boolean.TRUE.equals(client.getAuthorizationServicesEnabled())) {
            RepresentationToModel.createResourceServer(clientModel, session, true);
        }
        session.clientPolicy().triggerOnEvent(new DynamicClientRegisteredContext(context, clientModel, auth.getJwt(), realm));
        ClientRegistrationPolicyManager.triggerAfterRegister(context, registrationAuth, clientModel);
        client = ModelToRepresentation.toRepresentation(clientModel, session);
        client.setSecret(clientModel.getSecret());
        String registrationAccessToken = ClientRegistrationTokenUtils.updateRegistrationAccessToken(session, clientModel, registrationAuth);
        client.setRegistrationAccessToken(registrationAccessToken);
        if (auth.isInitialAccessToken()) {
            ClientInitialAccessModel initialAccessModel = auth.getInitialAccessModel();
            session.realms().decreaseRemainingCount(realm, initialAccessModel);
        }
        client.setDirectAccessGrantsEnabled(false);
        Stream<String> defaultRolesNames = clientModel.getDefaultRolesStream();
        if (defaultRolesNames != null) {
            client.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
        }
        event.client(client.getClientId()).success();
        return client;
    } catch (ModelDuplicateException e) {
        throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier in use", Response.Status.BAD_REQUEST);
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : ClientInitialAccessModel(org.keycloak.models.ClientInitialAccessModel) RegistrationAuth(org.keycloak.services.clientregistration.policy.RegistrationAuth) DynamicClientRegisteredContext(org.keycloak.services.clientpolicy.context.DynamicClientRegisteredContext) RealmManager(org.keycloak.services.managers.RealmManager) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ClientManager(org.keycloak.services.managers.ClientManager) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 3 with ClientManager

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

the class TokenEndpoint method clientCredentialsGrant.

public Response clientCredentialsGrant() {
    if (client.isBearerOnly()) {
        event.error(Errors.INVALID_CLIENT);
        throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Bearer-only client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
    }
    if (client.isPublicClient()) {
        event.error(Errors.INVALID_CLIENT);
        throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Public client not allowed to retrieve service account", Response.Status.UNAUTHORIZED);
    }
    if (!client.isServiceAccountsEnabled()) {
        event.error(Errors.INVALID_CLIENT);
        throw new CorsErrorResponseException(cors, OAuthErrorException.UNAUTHORIZED_CLIENT, "Client not enabled to retrieve service account", Response.Status.UNAUTHORIZED);
    }
    UserModel clientUser = session.users().getServiceAccount(client);
    if (clientUser == null || client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) {
        // May need to handle bootstrap here as well
        logger.debugf("Service account user for client '%s' not found or default protocol mapper for service account not found. Creating now", client.getClientId());
        new ClientManager(new RealmManager(session)).enableServiceAccount(client);
        clientUser = session.users().getServiceAccount(client);
    }
    String clientUsername = clientUser.getUsername();
    event.detail(Details.USERNAME, clientUsername);
    event.user(clientUser);
    if (!clientUser.isEnabled()) {
        event.error(Errors.USER_DISABLED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "User '" + clientUsername + "' disabled", Response.Status.UNAUTHORIZED);
    }
    String scope = getRequestedScopes();
    RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, false);
    AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
    authSession.setAuthenticatedUser(clientUser);
    authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
    authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);
    // persisting of userSession by default
    UserSessionModel.SessionPersistenceState sessionPersistenceState = UserSessionModel.SessionPersistenceState.PERSISTENT;
    boolean useRefreshToken = OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshTokenForClientCredentialsGrant();
    if (!useRefreshToken) {
        // we don't want to store a session hence we mark it as transient, see KEYCLOAK-9551
        sessionPersistenceState = UserSessionModel.SessionPersistenceState.TRANSIENT;
    }
    UserSessionModel userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, clientUser, clientUsername, clientConnection.getRemoteAddr(), ServiceAccountConstants.CLIENT_AUTH, false, null, null, sessionPersistenceState);
    event.session(userSession);
    AuthenticationManager.setClientScopesInSession(authSession);
    ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);
    // Notes about client details
    userSession.setNote(ServiceAccountConstants.CLIENT_ID, client.getClientId());
    userSession.setNote(ServiceAccountConstants.CLIENT_HOST, clientConnection.getRemoteHost());
    userSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, clientConnection.getRemoteAddr());
    try {
        session.clientPolicy().triggerOnEvent(new ServiceAccountTokenRequestContext(formParams, clientSessionCtx.getClientSession()));
    } catch (ClientPolicyException cpe) {
        event.error(cpe.getError());
        throw new CorsErrorResponseException(cors, cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
    updateUserSessionFromClientAuth(userSession);
    TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).generateAccessToken();
    // Make refresh token generation optional, see KEYCLOAK-9551
    if (useRefreshToken) {
        responseBuilder = responseBuilder.generateRefreshToken();
    } else {
        responseBuilder.getAccessToken().setSessionState(null);
    }
    checkMtlsHoKToken(responseBuilder, useRefreshToken);
    String scopeParam = clientSessionCtx.getClientSession().getNote(OAuth2Constants.SCOPE);
    if (TokenUtil.isOIDCRequest(scopeParam)) {
        responseBuilder.generateIDToken().generateAccessTokenHash();
    }
    // TODO : do the same as codeToToken()
    AccessTokenResponse res = responseBuilder.build();
    event.success();
    return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) RealmManager(org.keycloak.services.managers.RealmManager) ServiceAccountTokenRequestContext(org.keycloak.services.clientpolicy.context.ServiceAccountTokenRequestContext) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) UserModel(org.keycloak.models.UserModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) ClientManager(org.keycloak.services.managers.ClientManager) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) TokenManager(org.keycloak.protocol.oidc.TokenManager) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 4 with ClientManager

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

the class UserSessionProviderOfflineTest method testOnClientRemoved.

@Test
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR) -> {
        try {
            int started = Time.currentTime();
            AtomicReference<String> userSessionID = new AtomicReference<>();
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR1) -> {
                currentSession = sessionCR1;
                sessionManager = new UserSessionManager(currentSession);
                RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
                fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
                fooRealm.setSsoSessionIdleTimeout(1800);
                fooRealm.setSsoSessionMaxLifespan(36000);
                fooRealm.setOfflineSessionIdleTimeout(2592000);
                fooRealm.setOfflineSessionMaxLifespan(5184000);
                fooRealm.addClient("foo-app");
                fooRealm.addClient("bar-app");
                currentSession.users().addUser(fooRealm, "user3");
                UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
                userSessionID.set(userSession.getId());
                createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
                createClientSession(currentSession, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR2) -> {
                currentSession = sessionCR2;
                // Create offline currentSession
                RealmModel fooRealm = currentSession.realms().getRealm("foo");
                UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
                createOfflineSessionIncludeClientSessions(currentSession, userSession);
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR3) -> {
                currentSession = sessionCR3;
                RealmManager realmMgr = new RealmManager(currentSession);
                ClientManager clientMgr = new ClientManager(realmMgr);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                // Assert currentSession was persisted with both clientSessions
                UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
                assertSession(offlineSession, currentSession.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);
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR4) -> {
                currentSession = sessionCR4;
                RealmManager realmMgr = new RealmManager(currentSession);
                ClientManager clientMgr = new ClientManager(realmMgr);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                // Assert just one bar-app clientSession persisted now
                UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
                Assert.assertEquals(1, offlineSession.getAuthenticatedClientSessions().size());
                Assert.assertEquals("bar-app", offlineSession.getAuthenticatedClientSessions().values().iterator().next().getClient().getClientId());
                // Remove bar-app client
                ClientModel client = fooRealm.getClientByClientId("bar-app");
                clientMgr.removeClient(fooRealm, client);
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR5) -> {
                currentSession = sessionCR5;
                // Assert nothing loaded - userSession was removed as well because it was last userSession
                RealmManager realmMgr = new RealmManager(currentSession);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
                Assert.assertEquals(0, offlineSession.getAuthenticatedClientSessions().size());
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTearDown) -> {
                currentSession = sessionTearDown;
                RealmManager realmMgr = new RealmManager(currentSession);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
                // Remove user3
                new UserManager(currentSession).removeUser(fooRealm, user3);
                // Cleanup
                realmMgr = new RealmManager(currentSession);
                realmMgr.removeRealm(realmMgr.getRealm("foo"));
            });
        }
    });
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) UserSessionManager(org.keycloak.services.managers.UserSessionManager) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserManager(org.keycloak.models.UserManager) KeycloakSession(org.keycloak.models.KeycloakSession) ClientManager(org.keycloak.services.managers.ClientManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 5 with ClientManager

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

the class AuthenticationSessionProviderTest method testOnClientRemoved.

@Test
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
    AtomicReference<String> tab1ID = new AtomicReference<>();
    AtomicReference<String> tab2ID = new AtomicReference<>();
    AtomicReference<String> authSessionID = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
        KeycloakSession currentSession = sesRealmRemoved1;
        RealmModel realm = currentSession.realms().getRealm("test");
        authSessionID.set(currentSession.authenticationSessions().createRootAuthenticationSession(realm).getId());
        AuthenticationSessionModel authSession1 = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get()).createAuthenticationSession(realm.getClientByClientId("test-app"));
        AuthenticationSessionModel authSession2 = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get()).createAuthenticationSession(realm.getClientByClientId("third-party"));
        tab1ID.set(authSession1.getTabId());
        tab2ID.set(authSession2.getTabId());
        authSession1.setAuthNote("foo", "bar");
        authSession2.setAuthNote("foo", "baz");
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
        KeycloakSession currentSession = sesRealmRemoved1;
        RealmModel realm = currentSession.realms().getRealm("test");
        RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
        assertThat(rootAuthSession.getAuthenticationSessions().size(), is(2));
        assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("test-app"), tab1ID.get()).getAuthNote("foo"), is("bar"));
        assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("third-party"), tab2ID.get()).getAuthNote("foo"), is("baz"));
        new ClientManager(new RealmManager(currentSession)).removeClient(realm, realm.getClientByClientId("third-party"));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesRealmRemoved1) -> {
        KeycloakSession currentSession = sesRealmRemoved1;
        RealmModel realm = currentSession.realms().getRealm("test");
        RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, authSessionID.get());
        assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("test-app"), tab1ID.get()).getAuthNote("foo"), is("bar"));
        assertThat(rootAuthSession.getAuthenticationSession(realm.getClientByClientId("third-party"), tab2ID.get()), nullValue());
        // Revert client
        realm.addClient("third-party");
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ClientManager(org.keycloak.services.managers.ClientManager) 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

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