use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class QuarkusKeycloakApplication method createAdminUser.
private void createAdminUser() {
String adminUserName = System.getenv(KEYCLOAK_ADMIN_ENV_VAR);
String adminPassword = System.getenv(KEYCLOAK_ADMIN_PASSWORD_ENV_VAR);
if ((adminUserName == null || adminUserName.trim().length() == 0) || (adminPassword == null || adminPassword.trim().length() == 0)) {
return;
}
KeycloakSessionFactory sessionFactory = KeycloakApplication.getSessionFactory();
KeycloakSession session = sessionFactory.create();
KeycloakTransactionManager transaction = session.getTransactionManager();
try {
transaction.begin();
new ApplianceBootstrap(session).createMasterRealmUser(adminUserName, adminPassword);
ServicesLogger.LOGGER.addUserSuccess(adminUserName, Config.getAdminRealm());
transaction.commit();
} catch (IllegalStateException e) {
session.getTransactionManager().rollback();
ServicesLogger.LOGGER.addUserFailedUserExists(adminUserName, Config.getAdminRealm());
} catch (Throwable t) {
session.getTransactionManager().rollback();
ServicesLogger.LOGGER.addUserFailed(t, adminUserName, Config.getAdminRealm());
} finally {
session.close();
}
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class RepresentationToModel method toModel.
public static ResourceServer toModel(ResourceServerRepresentation rep, AuthorizationProvider authorization, ClientModel client) {
ResourceServerStore resourceServerStore = authorization.getStoreFactory().getResourceServerStore();
ResourceServer resourceServer;
ResourceServer existing = resourceServerStore.findByClient(client);
if (existing == null) {
resourceServer = resourceServerStore.create(client);
resourceServer.setAllowRemoteResourceManagement(true);
resourceServer.setPolicyEnforcementMode(PolicyEnforcementMode.ENFORCING);
} else {
resourceServer = existing;
}
resourceServer.setPolicyEnforcementMode(rep.getPolicyEnforcementMode());
resourceServer.setAllowRemoteResourceManagement(rep.isAllowRemoteResourceManagement());
DecisionStrategy decisionStrategy = rep.getDecisionStrategy();
if (decisionStrategy == null) {
decisionStrategy = DecisionStrategy.UNANIMOUS;
}
resourceServer.setDecisionStrategy(decisionStrategy);
for (ScopeRepresentation scope : rep.getScopes()) {
toModel(scope, resourceServer, authorization);
}
KeycloakSession session = authorization.getKeycloakSession();
RealmModel realm = authorization.getRealm();
for (ResourceRepresentation resource : rep.getResources()) {
ResourceOwnerRepresentation owner = resource.getOwner();
if (owner == null) {
owner = new ResourceOwnerRepresentation();
owner.setId(resourceServer.getId());
resource.setOwner(owner);
} else if (owner.getName() != null) {
UserModel user = session.users().getUserByUsername(realm, owner.getName());
if (user != null) {
owner.setId(user.getId());
}
}
toModel(resource, resourceServer, authorization);
}
importPolicies(authorization, resourceServer, rep.getPolicies(), null);
return resourceServer;
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class KeycloakModelUtils method runJobInTransaction.
/**
* Wrap given runnable job into KeycloakTransaction.
*
* @param factory
* @param task
*/
public static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task) {
KeycloakSession session = factory.create();
KeycloakTransaction tx = session.getTransactionManager();
try {
tx.begin();
task.run(session);
if (tx.isActive()) {
if (tx.getRollbackOnly()) {
tx.rollback();
} else {
tx.commit();
}
}
} catch (RuntimeException re) {
if (tx.isActive()) {
tx.rollback();
}
throw re;
} finally {
session.close();
}
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class UserConsentWithUserStorageModelTest method deleteClientScopeTest.
@Test
@ModelTest
public void deleteClientScopeTest(KeycloakSession session) {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesDelClScope1) -> {
KeycloakSession currentSession = sesDelClScope1;
RealmModel realm = currentSession.realms().getRealmByName("original");
ClientModel fooClient = realm.getClientByClientId("foo-client");
ClientScopeModel fooScope = KeycloakModelUtils.getClientScopeByName(realm, "foo");
realm.removeClientScope(fooScope.getId());
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesDelClScope2) -> {
KeycloakSession currentSession = sesDelClScope2;
RealmModel realm = currentSession.realms().getRealmByName("original");
ClientModel fooClient = realm.getClientByClientId("foo-client");
UserModel john = currentSession.users().getUserByUsername(realm, "john");
UserConsentModel johnConsent = currentSession.users().getConsentByClient(realm, john.getId(), fooClient.getId());
Assert.assertEquals(johnConsent.getGrantedClientScopes().size(), 0);
});
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class UserSessionProviderOfflineTest method testOfflineSessionsCrud.
@Test
@ModelTest
public void testOfflineSessionsCrud(KeycloakSession session) {
Map<String, Set<String>> offlineSessions = new HashMap<>();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud) -> {
// Create some online sessions in infinispan
reloadState(sessionCrud);
createSessions(sessionCrud);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud2) -> {
currentSession = sessionCrud2;
realm = currentSession.realms().getRealm("test");
sessionManager = new UserSessionManager(currentSession);
// Key is userSession ID, values are client UUIDS
// Persist 3 created userSessions and clientSessions as offline
ClientModel testApp = realm.getClientByClientId("test-app");
currentSession.sessions().getUserSessionsStream(realm, testApp).collect(Collectors.toList()).forEach(userSession -> offlineSessions.put(userSession.getId(), createOfflineSessionIncludeClientSessions(currentSession, userSession)));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud3) -> {
currentSession = sessionCrud3;
realm = currentSession.realms().getRealm("test");
sessionManager = new UserSessionManager(currentSession);
// Assert all previously saved offline sessions found
for (Map.Entry<String, Set<String>> entry : offlineSessions.entrySet()) {
UserSessionModel offlineSession = sessionManager.findOfflineUserSession(realm, entry.getKey());
Assert.assertNotNull(offlineSession);
Assert.assertEquals(offlineSession.getAuthenticatedClientSessions().keySet(), entry.getValue());
}
// Find clients with offline token
UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
Set<ClientModel> clients = sessionManager.findClientsWithOfflineToken(realm, user1);
Assert.assertEquals(clients.size(), 2);
for (ClientModel client : clients) {
Assert.assertTrue(client.getClientId().equals("test-app") || client.getClientId().equals("third-party"));
}
UserModel user2 = currentSession.users().getUserByUsername(realm, "user2");
clients = sessionManager.findClientsWithOfflineToken(realm, user2);
Assert.assertEquals(clients.size(), 1);
Assert.assertEquals("test-app", clients.iterator().next().getClientId());
// Test count
ClientModel testApp = realm.getClientByClientId("test-app");
ClientModel thirdparty = realm.getClientByClientId("third-party");
Assert.assertEquals(3, currentSession.sessions().getOfflineSessionsCount(realm, testApp));
Assert.assertEquals(1, currentSession.sessions().getOfflineSessionsCount(realm, thirdparty));
// Revoke "test-app" for user1
sessionManager.revokeOfflineToken(user1, testApp);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud4) -> {
currentSession = sessionCrud4;
realm = currentSession.realms().getRealm("test");
sessionManager = new UserSessionManager(currentSession);
// Assert userSession revoked
ClientModel thirdparty = realm.getClientByClientId("third-party");
List<UserSessionModel> thirdpartySessions = currentSession.sessions().getOfflineUserSessionsStream(realm, thirdparty, 0, 10).collect(Collectors.toList());
Assert.assertEquals(1, thirdpartySessions.size());
Assert.assertEquals("127.0.0.1", thirdpartySessions.get(0).getIpAddress());
Assert.assertEquals("user1", thirdpartySessions.get(0).getUser().getUsername());
UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
UserModel user2 = currentSession.users().getUserByUsername(realm, "user2");
Set<ClientModel> clients = sessionManager.findClientsWithOfflineToken(realm, user1);
Assert.assertEquals(1, clients.size());
Assert.assertEquals("third-party", clients.iterator().next().getClientId());
clients = sessionManager.findClientsWithOfflineToken(realm, user2);
Assert.assertEquals(1, clients.size());
Assert.assertEquals("test-app", clients.iterator().next().getClientId());
// Revoke the second currentSession for user1 too.
sessionManager.revokeOfflineToken(user1, thirdparty);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCrud5) -> {
currentSession = sessionCrud5;
realm = currentSession.realms().getRealm("test");
sessionManager = new UserSessionManager(currentSession);
ClientModel testApp = realm.getClientByClientId("test-app");
ClientModel thirdparty = realm.getClientByClientId("third-party");
// Accurate count now. All sessions of user1 cleared
Assert.assertEquals(1, currentSession.sessions().getOfflineSessionsCount(realm, testApp));
Assert.assertEquals(0, currentSession.sessions().getOfflineSessionsCount(realm, thirdparty));
List<UserSessionModel> testAppSessions = currentSession.sessions().getOfflineUserSessionsStream(realm, testApp, 0, 10).collect(Collectors.toList());
Assert.assertEquals(1, testAppSessions.size());
Assert.assertEquals("127.0.0.3", testAppSessions.get(0).getIpAddress());
Assert.assertEquals("user2", testAppSessions.get(0).getUser().getUsername());
UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
Set<ClientModel> clients = sessionManager.findClientsWithOfflineToken(realm, user1);
Assert.assertEquals(0, clients.size());
});
}
Aggregations