Search in sources :

Example 1 with KeycloakSession

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

the class RolePolicyProviderFactory method postInit.

@Override
public void postInit(KeycloakSessionFactory factory) {
    factory.register(event -> {
        if (event instanceof RoleRemovedEvent) {
            KeycloakSession keycloakSession = ((RoleRemovedEvent) event).getKeycloakSession();
            AuthorizationProvider provider = keycloakSession.getProvider(AuthorizationProvider.class);
            StoreFactory storeFactory = provider.getStoreFactory();
            PolicyStore policyStore = storeFactory.getPolicyStore();
            RoleModel removedRole = ((RoleRemovedEvent) event).getRole();
            RoleContainerModel container = removedRole.getContainer();
            ResourceServerStore resourceServerStore = storeFactory.getResourceServerStore();
            if (container instanceof RealmModel) {
                RealmModel realm = (RealmModel) container;
                realm.getClientsStream().forEach(clientModel -> updateResourceServer(clientModel, removedRole, resourceServerStore, policyStore));
            } else {
                ClientModel clientModel = (ClientModel) container;
                updateResourceServer(clientModel, removedRole, resourceServerStore, policyStore);
            }
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) KeycloakSession(org.keycloak.models.KeycloakSession) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) RoleRemovedEvent(org.keycloak.models.RoleContainerModel.RoleRemovedEvent) PolicyStore(org.keycloak.authorization.store.PolicyStore) RoleModel(org.keycloak.models.RoleModel) StoreFactory(org.keycloak.authorization.store.StoreFactory) RoleContainerModel(org.keycloak.models.RoleContainerModel)

Example 2 with KeycloakSession

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

the class UserPolicyProviderFactory method updateUsers.

private void updateUsers(Policy policy, AuthorizationProvider authorization, Set<String> users) {
    KeycloakSession session = authorization.getKeycloakSession();
    RealmModel realm = authorization.getRealm();
    UserProvider userProvider = session.users();
    Set<String> updatedUsers = new HashSet<>();
    if (users != null) {
        for (String userId : users) {
            UserModel user = null;
            try {
                user = userProvider.getUserByUsername(realm, userId);
            } catch (Exception ignore) {
            }
            if (user == null) {
                user = userProvider.getUserById(realm, userId);
            }
            if (user == null) {
                throw new RuntimeException("Error while updating policy [" + policy.getName() + "]. User [" + userId + "] could not be found.");
            }
            updatedUsers.add(user.getId());
        }
    }
    try {
        policy.putConfig("users", JsonSerialization.writeValueAsString(updatedUsers));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to serialize users", cause);
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserProvider(org.keycloak.models.UserProvider) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 3 with KeycloakSession

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

the class JpaMapStorageProviderFactory method update.

private void update(Class<?> modelType, Connection connection, KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession lockSession) -> {
        // TODO locking tables based on modelType: https://github.com/keycloak/keycloak/issues/9388
        DBLockProvider dbLock = session.getProvider(DBLockProvider.class);
        dbLock.waitForLock(DBLockProvider.Namespace.DATABASE);
        try {
            session.getProvider(MapJpaUpdaterProvider.class).update(modelType, connection, config.get("schema"));
        } finally {
            dbLock.releaseLock();
        }
    });
}
Also used : KeycloakSession(org.keycloak.models.KeycloakSession) MapJpaUpdaterProvider(org.keycloak.models.map.storage.jpa.updater.MapJpaUpdaterProvider) DBLockProvider(org.keycloak.models.dblock.DBLockProvider)

Example 4 with KeycloakSession

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

the class IdpVerifyAccountLinkActionTokenHandler method handleToken.

@Override
public Response handleToken(IdpVerifyAccountLinkActionToken token, ActionTokenContext<IdpVerifyAccountLinkActionToken> tokenContext) {
    UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
    EventBuilder event = tokenContext.getEvent();
    final UriInfo uriInfo = tokenContext.getUriInfo();
    final RealmModel realm = tokenContext.getRealm();
    final KeycloakSession session = tokenContext.getSession();
    event.event(EventType.IDENTITY_PROVIDER_LINK_ACCOUNT).detail(Details.EMAIL, user.getEmail()).detail(Details.IDENTITY_PROVIDER, token.getIdentityProviderAlias()).detail(Details.IDENTITY_PROVIDER_USERNAME, token.getIdentityProviderUsername()).success();
    AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
    if (tokenContext.isAuthenticationSessionFresh()) {
        token.setOriginalCompoundAuthenticationSessionId(token.getCompoundAuthenticationSessionId());
        String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
        token.setCompoundAuthenticationSessionId(authSessionEncodedId);
        UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo), authSession.getClient().getClientId(), authSession.getTabId());
        String confirmUri = builder.build(realm.getName()).toString();
        return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.CONFIRM_ACCOUNT_LINKING, token.getIdentityProviderUsername(), token.getIdentityProviderAlias()).setAttribute(Constants.TEMPLATE_ATTR_ACTION_URI, confirmUri).createInfoPage();
    }
    // verify user email as we know it is valid as this entry point would never have gotten here.
    user.setEmailVerified(true);
    if (token.getOriginalCompoundAuthenticationSessionId() != null) {
        AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
        asm.removeAuthenticationSession(realm, authSession, true);
        AuthenticationSessionCompoundId compoundId = AuthenticationSessionCompoundId.encoded(token.getOriginalCompoundAuthenticationSessionId());
        ClientModel originalClient = realm.getClientById(compoundId.getClientUUID());
        authSession = asm.getAuthenticationSessionByIdAndClient(realm, compoundId.getRootSessionId(), originalClient, compoundId.getTabId());
        if (authSession != null) {
            authSession.setAuthNote(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername());
        } else {
            session.authenticationSessions().updateNonlocalSessionAuthNotes(compoundId, Collections.singletonMap(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername()));
        }
        return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.IDENTITY_PROVIDER_LINK_SUCCESS, token.getIdentityProviderAlias(), token.getIdentityProviderUsername()).setAttribute(Constants.SKIP_LINK, true).createInfoPage();
    }
    authSession.setAuthNote(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername());
    return tokenContext.brokerFlow(null, null, authSession.getAuthNote(AuthenticationProcessor.CURRENT_FLOW_PATH));
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) UriBuilder(javax.ws.rs.core.UriBuilder) AuthenticationSessionCompoundId(org.keycloak.sessions.AuthenticationSessionCompoundId) UriInfo(javax.ws.rs.core.UriInfo)

Example 5 with KeycloakSession

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

the class VerifyEmailActionTokenHandler method handleToken.

@Override
public Response handleToken(VerifyEmailActionToken token, ActionTokenContext<VerifyEmailActionToken> tokenContext) {
    UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
    EventBuilder event = tokenContext.getEvent();
    event.event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, user.getEmail());
    AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
    final UriInfo uriInfo = tokenContext.getUriInfo();
    final RealmModel realm = tokenContext.getRealm();
    final KeycloakSession session = tokenContext.getSession();
    if (tokenContext.isAuthenticationSessionFresh()) {
        // Update the authentication session in the token
        token.setCompoundOriginalAuthenticationSessionId(token.getCompoundAuthenticationSessionId());
        String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
        token.setCompoundAuthenticationSessionId(authSessionEncodedId);
        UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo), authSession.getClient().getClientId(), authSession.getTabId());
        String confirmUri = builder.build(realm.getName()).toString();
        return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.CONFIRM_EMAIL_ADDRESS_VERIFICATION, user.getEmail()).setAttribute(Constants.TEMPLATE_ATTR_ACTION_URI, confirmUri).createInfoPage();
    }
    // verify user email as we know it is valid as this entry point would never have gotten here.
    user.setEmailVerified(true);
    user.removeRequiredAction(RequiredAction.VERIFY_EMAIL);
    authSession.removeRequiredAction(RequiredAction.VERIFY_EMAIL);
    event.success();
    if (token.getCompoundOriginalAuthenticationSessionId() != null) {
        AuthenticationSessionManager asm = new AuthenticationSessionManager(tokenContext.getSession());
        asm.removeAuthenticationSession(tokenContext.getRealm(), authSession, true);
        return tokenContext.getSession().getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.EMAIL_VERIFIED).createInfoPage();
    }
    tokenContext.setEvent(event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN));
    String nextAction = AuthenticationManager.nextRequiredAction(session, authSession, tokenContext.getRequest(), event);
    return AuthenticationManager.redirectToRequiredActions(session, realm, authSession, uriInfo, nextAction);
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) KeycloakSession(org.keycloak.models.KeycloakSession) UriBuilder(javax.ws.rs.core.UriBuilder) UriInfo(javax.ws.rs.core.UriInfo)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)189 RealmModel (org.keycloak.models.RealmModel)136 UserModel (org.keycloak.models.UserModel)78 Test (org.junit.Test)76 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)61 ClientModel (org.keycloak.models.ClientModel)58 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)53 List (java.util.List)34 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 Collectors (java.util.stream.Collectors)21 IOException (java.io.IOException)20 Map (java.util.Map)19 UserSessionModel (org.keycloak.models.UserSessionModel)19 ArrayList (java.util.ArrayList)18 ClientScopeModel (org.keycloak.models.ClientScopeModel)18 RoleModel (org.keycloak.models.RoleModel)18 Set (java.util.Set)16 RealmManager (org.keycloak.services.managers.RealmManager)16 HashMap (java.util.HashMap)14 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)14