use of org.keycloak.models.RealmModel 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);
}
}
use of org.keycloak.models.RealmModel in project keycloak by keycloak.
the class LoginRealmBeanTest method exposeActionTokenLifespansInMinutesTest.
@Test
public void exposeActionTokenLifespansInMinutesTest() {
RealmModel realmModel = (RealmModel) Proxy.newProxyInstance(LoginRealmBeanTest.class.getClassLoader(), new Class[] { RealmModel.class }, (proxy, method, args) -> {
if (method.getName().matches("getActionTokenGeneratedByUserLifespan|getIdpVerifyAccountLinkActionTokenLifespan|getResetCredentialsActionTokenLifespan|getVerifyEmailActionTokenLifespan")) {
return 300;
}
return null;
});
RealmBean realmBean = new RealmBean(realmModel);
Assert.assertEquals(5, realmBean.getActionTokenGeneratedByUserLifespanMinutes());
Assert.assertEquals(5, realmBean.getIdpVerifyAccountLinkActionTokenLifespanMinutes());
Assert.assertEquals(5, realmBean.getResetCredentialsActionTokenLifespanMinutes());
Assert.assertEquals(5, realmBean.getVerifyEmailActionTokenLifespanMinutes());
}
use of org.keycloak.models.RealmModel in project keycloak by keycloak.
the class LastSessionRefreshCrossDCTest method testLastSessionRefreshUpdate.
@Test
public void testLastSessionRefreshUpdate(@JmxInfinispanCacheStatistics(dc = DC.FIRST, managementPortProperty = "cache.server.management.port", cacheName = InfinispanConnectionProvider.USER_SESSION_CACHE_NAME) InfinispanStatistics sessionCacheDc1Stats, @JmxInfinispanCacheStatistics(dc = DC.SECOND, managementPortProperty = "cache.server.2.management.port", cacheName = InfinispanConnectionProvider.USER_SESSION_CACHE_NAME) InfinispanStatistics sessionCacheDc2Stats, @JmxInfinispanCacheStatistics(dc = DC.FIRST, managementPortProperty = "cache.server.management.port", cacheName = InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME) InfinispanStatistics clientSessionCacheDc1Stats, @JmxInfinispanCacheStatistics(dc = DC.SECOND, managementPortProperty = "cache.server.2.management.port", cacheName = InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME) InfinispanStatistics clientSessionCacheDc2Stats) {
// Set the infinispan testTimeService on all started auth servers
setInfinispanTestTimeServiceOnAllStartedAuthServers();
try {
// Ensure to remove all current sessions and offline sessions
setTimeOffset(10000000);
getTestingClientForStartedNodeInDc(0).testing("test").removeExpired("test");
getTestingClientForStartedNodeInDc(1).testing("test").removeExpired("test");
setTimeOffset(0);
sessionCacheDc1Stats.reset();
sessionCacheDc2Stats.reset();
clientSessionCacheDc1Stats.reset();
clientSessionCacheDc2Stats.reset();
// Disable DC2 on loadbalancer
disableDcOnLoadBalancer(DC.SECOND);
// Get statistics
AtomicLong sessionStoresDc1 = new AtomicLong(getStores(sessionCacheDc1Stats));
AtomicLong sessionStoresDc2 = new AtomicLong(getStores(sessionCacheDc2Stats));
AtomicLong clientSessionStoresDc1 = new AtomicLong(getStores(clientSessionCacheDc1Stats));
AtomicLong clientSessionStoresDc2 = new AtomicLong(getStores(clientSessionCacheDc2Stats));
AtomicInteger lsrDc1 = new AtomicInteger(-1);
AtomicInteger lsrDc2 = new AtomicInteger(-1);
// Login
OAuthClient.AuthorizationEndpointResponse response1 = oauth.doLogin("test-user@localhost", "password");
String code = response1.getCode();
OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
Assert.assertNotNull(tokenResponse.getAccessToken());
String sessionId = oauth.verifyToken(tokenResponse.getAccessToken()).getSessionState();
String refreshToken1 = tokenResponse.getRefreshToken();
// Assert statistics - sessions created on both DCs and created on remoteCaches too
assertStatistics("After session created", sessionId, sessionCacheDc1Stats, sessionCacheDc2Stats, clientSessionCacheDc1Stats, clientSessionCacheDc2Stats, sessionStoresDc1, sessionStoresDc2, clientSessionStoresDc1, clientSessionStoresDc2, lsrDc1, lsrDc2, true, true, true, false);
// Set time offset
setTimeOffset(100);
// refresh token on DC1
tokenResponse = oauth.doRefreshTokenRequest(refreshToken1, "password");
String refreshToken2 = tokenResponse.getRefreshToken();
Assert.assertNotNull(refreshToken2);
// Assert statistics - sessions updated on both DC1 and DC2. RemoteCaches not updated
assertStatistics("After refresh at time 100", sessionId, sessionCacheDc1Stats, sessionCacheDc2Stats, clientSessionCacheDc1Stats, clientSessionCacheDc2Stats, sessionStoresDc1, sessionStoresDc2, clientSessionStoresDc1, clientSessionStoresDc2, lsrDc1, lsrDc2, true, true, false, false);
// Set time offset
setTimeOffset(110);
// refresh token on DC1
tokenResponse = oauth.doRefreshTokenRequest(refreshToken1, "password");
String refreshToken3 = tokenResponse.getRefreshToken();
Assert.assertNotNull(refreshToken3);
// Assert statistics - sessions updated just on DC1.
// Update of DC2 is postponed (It's just 10 seconds since last message). RemoteCaches not updated
assertStatistics("After refresh at time 110", sessionId, sessionCacheDc1Stats, sessionCacheDc2Stats, clientSessionCacheDc1Stats, clientSessionCacheDc2Stats, sessionStoresDc1, sessionStoresDc2, clientSessionStoresDc1, clientSessionStoresDc2, lsrDc1, lsrDc2, true, false, false, false);
// 31 minutes after "100". Session should be still valid and not yet expired (RefreshToken will be invalid due the expiration on the JWT itself. Hence not testing refresh here)
setTimeOffset(1960);
boolean sessionValid = getTestingClientForStartedNodeInDc(1).server("test").fetch((KeycloakSession session) -> {
RealmModel realm = session.realms().getRealmByName("test");
UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
return AuthenticationManager.isSessionValid(realm, userSession);
}, Boolean.class);
Assert.assertTrue(sessionValid);
getTestingClientForStartedNodeInDc(1).testing("test").removeExpired("test");
// Assert statistics - nothing was updated. No refresh happened and nothing was cleared during "removeExpired"
assertStatistics("After checking valid at time 1960", sessionId, sessionCacheDc1Stats, sessionCacheDc2Stats, clientSessionCacheDc1Stats, clientSessionCacheDc2Stats, sessionStoresDc1, sessionStoresDc2, clientSessionStoresDc1, clientSessionStoresDc2, lsrDc1, lsrDc2, false, false, false, false);
// 35 minutes after "100". Session not valid and will be expired by the cleaner
setTimeOffset(2200);
sessionValid = getTestingClientForStartedNodeInDc(1).server("test").fetch((KeycloakSession session) -> {
RealmModel realm = session.realms().getRealmByName("test");
UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
return AuthenticationManager.isSessionValid(realm, userSession);
}, Boolean.class);
Assert.assertFalse(sessionValid);
// 2000 seconds after the previous. This should ensure that session would be expired from the cache due the invalid maxIdle.
// Previous read at time 2200 "refreshed" the maxIdle in the infinispan cache. This shouldn't happen in reality as an attempt to call refreshToken request on invalid session does backchannelLogout
setTimeOffset(4200);
getTestingClientForStartedNodeInDc(1).testing("test").removeExpired("test");
// Session should be removed on both DCs
try {
getTestingClientForStartedNodeInDc(0).testing("test").getLastSessionRefresh("test", sessionId, false);
Assert.fail("It wasn't expected to find the session " + sessionId);
} catch (NotFoundException nfe) {
// Expected
}
try {
getTestingClientForStartedNodeInDc(1).testing("test").getLastSessionRefresh("test", sessionId, false);
Assert.fail("It wasn't expected to find the session " + sessionId);
} catch (NotFoundException nfe) {
// Expected
}
} finally {
// Revert time service
revertInfinispanTestTimeServiceOnAllStartedAuthServers();
}
}
use of org.keycloak.models.RealmModel in project keycloak by keycloak.
the class LDAPGroupMapper2WaySyncTest method test01_syncNoPreserveGroupInheritance.
@Test
public void test01_syncNoPreserveGroupInheritance() throws Exception {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel realm = ctx.getRealm();
ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ctx.getLdapModel(), "groupsMapper");
LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
// Update group mapper to skip preserve inheritance and check it will pass now
LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "false");
realm.updateComponent(mapperModel);
// Sync from Keycloak into LDAP
SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromKeycloakToFederationProvider(realm);
LDAPTestAsserts.assertSyncEquals(syncResult, 4, 0, 0, 0);
});
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel realm = ctx.getRealm();
// Delete all KC groups now
removeAllModelGroups(realm);
Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group1"));
Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group11"));
Assert.assertNull(KeycloakModelUtils.findGroupByPath(realm, "/group2"));
});
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel realm = ctx.getRealm();
ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ctx.getLdapModel(), "groupsMapper");
// Sync from LDAP back into Keycloak
SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm);
LDAPTestAsserts.assertSyncEquals(syncResult, 4, 0, 0, 0);
});
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel realm = ctx.getRealm();
String descriptionAttrName = LDAPTestUtils.getGroupDescriptionLDAPAttrName(ctx.getLdapProvider());
ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ctx.getLdapModel(), "groupsMapper");
// Assert groups are imported to keycloak. All are at top level
GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(realm, "/group1");
GroupModel kcGroup11 = KeycloakModelUtils.findGroupByPath(realm, "/group11");
GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(realm, "/group12");
GroupModel kcGroup2 = KeycloakModelUtils.findGroupByPath(realm, "/group2");
Assert.assertEquals(0, kcGroup1.getSubGroupsStream().count());
Assert.assertEquals("group1 - description1", kcGroup1.getFirstAttribute(descriptionAttrName));
Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName));
Assert.assertEquals("group12 - description12", kcGroup12.getFirstAttribute(descriptionAttrName));
Assert.assertNull(kcGroup2.getFirstAttribute(descriptionAttrName));
// test drop non-existing works
testDropNonExisting(session, ctx, mapperModel);
});
}
use of org.keycloak.models.RealmModel in project keycloak by keycloak.
the class LDAPGroupMapper2WaySyncTest method testDropNonExisting.
private static void testDropNonExisting(KeycloakSession session, LDAPTestContext ctx, ComponentModel mapperModel) {
RealmModel realm = ctx.getRealm();
// Put some group directly to LDAP
LDAPTestUtils.createLDAPGroup(session, realm, ctx.getLdapModel(), "group3");
// Sync and assert our group is still in LDAP
SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromKeycloakToFederationProvider(realm);
LDAPTestAsserts.assertSyncEquals(syncResult, 0, 4, 0, 0);
Assert.assertNotNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3"));
// Change config to drop non-existing groups
LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.DROP_NON_EXISTING_GROUPS_DURING_SYNC, "true");
realm.updateComponent(mapperModel);
// Sync and assert group removed from LDAP
syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromKeycloakToFederationProvider(realm);
LDAPTestAsserts.assertSyncEquals(syncResult, 0, 4, 1, 0);
Assert.assertNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3"));
}
Aggregations