use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class ClientPoliciesUtil method getValidatedGlobalClientProfilesRepresentation.
/**
* get validated and modified global (built-in) client profiles set on keycloak app as representation.
* it is loaded from json file enclosed in keycloak's binary.
* not return null.
*/
static List<ClientProfileRepresentation> getValidatedGlobalClientProfilesRepresentation(KeycloakSession session, InputStream is) throws ClientPolicyException {
// load builtin client profiles representation
ClientProfilesRepresentation proposedProfilesRep = null;
try {
proposedProfilesRep = JsonSerialization.readValue(is, ClientProfilesRepresentation.class);
} catch (Exception e) {
throw new ClientPolicyException("failed to deserialize global proposed client profiles json string.", e.getMessage());
}
if (proposedProfilesRep == null) {
return Collections.emptyList();
}
// no profile contained (it is valid)
List<ClientProfileRepresentation> proposedProfileRepList = proposedProfilesRep.getProfiles();
if (proposedProfileRepList == null || proposedProfileRepList.isEmpty()) {
return Collections.emptyList();
}
// duplicated profile name is not allowed.
if (proposedProfileRepList.size() != proposedProfileRepList.stream().map(i -> i.getName()).distinct().count()) {
throw new ClientPolicyException("proposed global client profile name duplicated.");
}
// construct validated and modified profiles from builtin profiles in JSON file enclosed in keycloak binary.
List<ClientProfileRepresentation> updatingProfileList = new LinkedList<>();
for (ClientProfileRepresentation proposedProfileRep : proposedProfilesRep.getProfiles()) {
if (proposedProfileRep.getName() == null) {
throw new ClientPolicyException("client profile without its name not allowed.");
}
ClientProfileRepresentation profileRep = new ClientProfileRepresentation();
profileRep.setName(proposedProfileRep.getName());
profileRep.setDescription(proposedProfileRep.getDescription());
// to prevent returning null
profileRep.setExecutors(new ArrayList<>());
if (proposedProfileRep.getExecutors() != null) {
for (ClientPolicyExecutorRepresentation executorRep : proposedProfileRep.getExecutors()) {
// Skip the check if feature is disabled as then the executor implementations are disabled
if (Profile.isFeatureEnabled(Profile.Feature.CLIENT_POLICIES) && !isValidExecutor(session, executorRep.getExecutorProviderId())) {
throw new ClientPolicyException("proposed client profile contains the executor with its invalid configuration.");
}
profileRep.getExecutors().add(executorRep);
}
}
updatingProfileList.add(profileRep);
}
return updatingProfileList;
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class ClientStorageTest method testRefreshWithOfflineToken.
private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken offlineToken, String offlineTokenString, final String sessionId, String userId) {
// Change offset to big value to ensure userSession expired
setTimeOffset(99999);
Assert.assertFalse(oldToken.isActive());
Assert.assertTrue(offlineToken.isActive());
// Assert userSession expired
testingClient.testing().removeExpired("test");
try {
testingClient.testing().removeUserSession("test", sessionId);
} catch (NotFoundException nfe) {
// Ignore
}
OAuthClient.AccessTokenResponse response = oauth.doRefreshTokenRequest(offlineTokenString, "password");
AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken());
String offlineUserSessionId = testingClient.server().fetch((KeycloakSession session) -> session.sessions().getOfflineUserSession(session.realms().getRealmByName("test"), offlineToken.getSessionState()).getId(), String.class);
Assert.assertEquals(200, response.getStatusCode());
Assert.assertEquals(offlineUserSessionId, refreshedToken.getSessionState());
// Assert new refreshToken in the response
String newRefreshToken = response.getRefreshToken();
Assert.assertNotNull(newRefreshToken);
Assert.assertNotEquals(oldToken.getId(), refreshedToken.getId());
Assert.assertEquals(userId, refreshedToken.getSubject());
Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole(Constants.OFFLINE_ACCESS_ROLE));
EventRepresentation refreshEvent = events.expectRefresh(offlineToken.getId(), sessionId).client("hardcoded-client").user(userId).removeDetail(Details.UPDATED_REFRESH_TOKEN_ID).detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE).assertEvent();
Assert.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID));
setTimeOffset(0);
return newRefreshToken;
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class OfflineSessionPersistenceTest method createEnvironment.
@Override
public void createEnvironment(KeycloakSession s) {
RealmModel realm = prepareRealm(s, "realm");
this.realmId = realm.getId();
userIds = IntStream.range(0, USER_COUNT).mapToObj(i -> s.users().addUser(realm, "user-" + i)).map(UserModel::getId).collect(Collectors.toList());
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class UserSyncTest method createEnvironment.
@Override
public void createEnvironment(KeycloakSession s) {
inComittedTransaction(session -> {
RealmModel realm = session.realms().createRealm("realm");
realm.setDefaultRole(session.roles().addRealmRole(realm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm.getName()));
this.realmId = realm.getId();
});
getParameters(UserStorageProviderModel.class).forEach(fs -> inComittedTransaction(session -> {
if (userFederationId != null || !fs.isImportEnabled())
return;
RealmModel realm = session.realms().getRealm(realmId);
fs.setParentId(realmId);
ComponentModel res = realm.addComponentModel(fs);
// Check if the provider implements ImportSynchronization interface
UserStorageProviderFactory userStorageProviderFactory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, res.getProviderId());
if (!ImportSynchronization.class.isAssignableFrom(userStorageProviderFactory.getClass())) {
return;
}
userFederationId = res.getId();
log.infof("Added %s user federation provider: %s", fs.getName(), res.getId());
}));
assumeThat("Cannot run UserSyncTest because there is no user federation provider that supports sync", userFederationId, notNullValue());
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class DBLockTest method simpleNestedLockTest.
@Test
public void simpleNestedLockTest() throws Exception {
inComittedTransaction(1, (session, i) -> {
// first session lock DATABASE
DBLockProvider dbLock1 = new DBLockManager(session).getDBLock();
dbLock1.waitForLock(DBLockProvider.Namespace.DATABASE);
try {
Assert.assertEquals(DBLockProvider.Namespace.DATABASE, dbLock1.getCurrentLock());
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLC2) -> {
// a second session/dblock-provider can lock another namespace OFFLINE_SESSIONS
DBLockProvider dbLock2 = new DBLockManager(sessionLC2).getDBLock();
dbLock2.waitForLock(DBLockProvider.Namespace.OFFLINE_SESSIONS);
try {
// getCurrentLock is local, each provider instance has one
Assert.assertEquals(DBLockProvider.Namespace.OFFLINE_SESSIONS, dbLock2.getCurrentLock());
} finally {
dbLock2.releaseLock();
}
Assert.assertNull(dbLock2.getCurrentLock());
});
} finally {
dbLock1.releaseLock();
}
Assert.assertNull(dbLock1.getCurrentLock());
return null;
});
}
Aggregations