use of org.keycloak.models.KeycloakSessionFactory in project keycloak by keycloak.
the class IdentityBrokerService method updateFederatedIdentity.
private void updateFederatedIdentity(BrokeredIdentityContext context, UserModel federatedUser) {
FederatedIdentityModel federatedIdentityModel = this.session.users().getFederatedIdentity(this.realmModel, federatedUser, context.getIdpConfig().getAlias());
if (context.getIdpConfig().getSyncMode() == IdentityProviderSyncMode.FORCE) {
setBasicUserAttributes(context, federatedUser);
}
// Skip DB write if tokens are null or equal
updateToken(context, federatedUser, federatedIdentityModel);
context.getIdp().updateBrokeredUser(session, realmModel, federatedUser, context);
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
realmModel.getIdentityProviderMappersByAliasStream(context.getIdpConfig().getAlias()).forEach(mapper -> {
IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
IdentityProviderMapperSyncModeDelegate.delegateUpdateBrokeredUser(session, realmModel, federatedUser, mapper, context, target);
});
}
use of org.keycloak.models.KeycloakSessionFactory in project keycloak by keycloak.
the class IdentityBrokerService method afterFirstBrokerLogin.
private Response afterFirstBrokerLogin(AuthenticationSessionModel authSession) {
try {
this.event.detail(Details.CODE_ID, authSession.getParentSession().getId()).removeDetail("auth_method");
SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
if (serializedCtx == null) {
throw new IdentityBrokerException("Not found serialized context in clientSession");
}
BrokeredIdentityContext context = serializedCtx.deserialize(session, authSession);
String providerId = context.getIdpConfig().getAlias();
event.detail(Details.IDENTITY_PROVIDER, providerId);
event.detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
// Ensure the first-broker-login flow was successfully finished
String authProvider = authSession.getAuthNote(AbstractIdpAuthenticator.FIRST_BROKER_LOGIN_SUCCESS);
if (authProvider == null || !authProvider.equals(providerId)) {
throw new IdentityBrokerException("Invalid request. Not found the flag that first-broker-login flow was finished");
}
// firstBrokerLogin workflow finished. Removing note now
authSession.removeAuthNote(AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
UserModel federatedUser = authSession.getAuthenticatedUser();
if (federatedUser == null) {
throw new IdentityBrokerException("Couldn't found authenticated federatedUser in authentication session");
}
event.user(federatedUser);
event.detail(Details.USERNAME, federatedUser.getUsername());
if (context.getIdpConfig().isAddReadTokenRoleOnCreate()) {
ClientModel brokerClient = realmModel.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
if (brokerClient == null) {
throw new IdentityBrokerException("Client 'broker' not available. Maybe realm has not migrated to support the broker token exchange service");
}
RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE);
federatedUser.grantRole(readTokenRole);
}
// Add federated identity link here
FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(context.getIdpConfig().getAlias(), context.getId(), context.getUsername(), context.getToken());
session.users().addFederatedIdentity(realmModel, federatedUser, federatedIdentityModel);
String isRegisteredNewUser = authSession.getAuthNote(AbstractIdpAuthenticator.BROKER_REGISTERED_NEW_USER);
if (Boolean.parseBoolean(isRegisteredNewUser)) {
logger.debugf("Registered new user '%s' after first login with identity provider '%s'. Identity provider username is '%s' . ", federatedUser.getUsername(), providerId, context.getUsername());
context.getIdp().importNewUser(session, realmModel, federatedUser, context);
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
realmModel.getIdentityProviderMappersByAliasStream(providerId).forEach(mapper -> {
IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
target.importNewUser(session, realmModel, federatedUser, mapper, context);
});
if (context.getIdpConfig().isTrustEmail() && !Validation.isBlank(federatedUser.getEmail()) && !Boolean.parseBoolean(authSession.getAuthNote(AbstractIdpAuthenticator.UPDATE_PROFILE_EMAIL_CHANGED))) {
logger.debugf("Email verified automatically after registration of user '%s' through Identity provider '%s' ", federatedUser.getUsername(), context.getIdpConfig().getAlias());
federatedUser.setEmailVerified(true);
}
event.event(EventType.REGISTER).detail(Details.REGISTER_METHOD, "broker").detail(Details.EMAIL, federatedUser.getEmail()).success();
} else {
logger.debugf("Linked existing keycloak user '%s' with identity provider '%s' . Identity provider username is '%s' .", federatedUser.getUsername(), providerId, context.getUsername());
event.event(EventType.FEDERATED_IDENTITY_LINK).success();
updateFederatedIdentity(context, federatedUser);
}
return finishOrRedirectToPostBrokerLogin(authSession, context, true);
} catch (Exception e) {
return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
}
}
use of org.keycloak.models.KeycloakSessionFactory in project keycloak by keycloak.
the class InfinispanAuthenticationSessionProviderFactory method registerClusterListeners.
protected void registerClusterListeners(KeycloakSession session) {
KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
ClusterProvider cluster = session.getProvider(ClusterProvider.class);
cluster.registerListener(REALM_REMOVED_AUTHSESSION_EVENT, new AbstractAuthSessionClusterListener<RealmRemovedSessionEvent>(sessionFactory) {
@Override
protected void eventReceived(KeycloakSession session, InfinispanAuthenticationSessionProvider provider, RealmRemovedSessionEvent sessionEvent) {
provider.onRealmRemovedEvent(sessionEvent.getRealmId());
}
});
cluster.registerListener(CLIENT_REMOVED_AUTHSESSION_EVENT, new AbstractAuthSessionClusterListener<ClientRemovedSessionEvent>(sessionFactory) {
@Override
protected void eventReceived(KeycloakSession session, InfinispanAuthenticationSessionProvider provider, ClientRemovedSessionEvent sessionEvent) {
provider.onClientRemovedEvent(sessionEvent.getRealmId(), sessionEvent.getClientUuid());
}
});
log.debug("Registered cluster listeners");
}
use of org.keycloak.models.KeycloakSessionFactory in project keycloak by keycloak.
the class KeycloakModelTest method closeKeycloakSessionFactory.
public static synchronized void closeKeycloakSessionFactory() {
KeycloakSessionFactory f = getFactory();
setFactory(null);
if (f != null) {
LOG.debugf("Closing %s", f);
f.close();
}
}
use of org.keycloak.models.KeycloakSessionFactory in project keycloak by keycloak.
the class DBLockTest method testLockConcurrentlyInternal.
private void testLockConcurrentlyInternal(KeycloakSession sessionLC, DBLockProvider.Namespace lock) {
long startupTime = System.currentTimeMillis();
final Semaphore semaphore = new Semaphore();
final KeycloakSessionFactory sessionFactory = sessionLC.getKeycloakSessionFactory();
List<Thread> threads = new LinkedList<>();
for (int i = 0; i < THREADS_COUNT; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < ITERATIONS_PER_THREAD; j++) {
try {
KeycloakModelUtils.runJobInTransaction(sessionFactory, session1 -> lock(session1, lock, semaphore));
} catch (RuntimeException e) {
semaphore.setException(e);
throw e;
}
}
});
threads.add(thread);
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long took = (System.currentTimeMillis() - startupTime);
log.infof("DBLockTest executed in %d ms with total counter %d. THREADS_COUNT=%d, ITERATIONS_PER_THREAD=%d", took, semaphore.getTotal(), THREADS_COUNT, ITERATIONS_PER_THREAD);
Assert.assertEquals(THREADS_COUNT * ITERATIONS_PER_THREAD, semaphore.getTotal());
Assert.assertNull(semaphore.getException());
}
Aggregations