use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class DockerAuthV2Protocol method authenticated.
@Override
public Response authenticated(final AuthenticationSessionModel authSession, final UserSessionModel userSession, final ClientSessionContext clientSessionCtx) {
// First, create a base response token with realm + user values populated
final AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
final ClientModel client = clientSession.getClient();
DockerResponseToken responseToken = new DockerResponseToken().id(KeycloakModelUtils.generateId()).type(TokenUtil.TOKEN_TYPE_BEARER).issuer(authSession.getClientNote(DockerAuthV2Protocol.ISSUER)).subject(userSession.getUser().getUsername()).issuedNow().audience(client.getClientId()).issuedFor(client.getClientId());
// since realm access token is given in seconds
final int accessTokenLifespan = realm.getAccessTokenLifespan();
responseToken.notBefore(responseToken.getIssuedAt()).expiration(responseToken.getIssuedAt() + accessTokenLifespan);
// Next, allow mappers to decorate the token to add/remove scopes as appropriate
AtomicReference<DockerResponseToken> finalResponseToken = new AtomicReference<>(responseToken);
ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx).filter(mapper -> mapper.getValue() instanceof DockerAuthV2AttributeMapper).filter(mapper -> ((DockerAuthV2AttributeMapper) mapper.getValue()).appliesTo(finalResponseToken.get())).forEach(mapper -> finalResponseToken.set(((DockerAuthV2AttributeMapper) mapper.getValue()).transformDockerResponseToken(finalResponseToken.get(), mapper.getKey(), session, userSession, clientSession)));
responseToken = finalResponseToken.get();
try {
// Finally, construct the response to the docker client with the token + metadata
if (event.getEvent() != null && EventType.LOGIN.equals(event.getEvent().getType())) {
final KeyManager.ActiveRsaKey activeKey = session.keys().getActiveRsaKey(realm);
final String encodedToken = new JWSBuilder().kid(new DockerKeyIdentifier(activeKey.getPublicKey()).toString()).type("JWT").jsonContent(responseToken).rsa256(activeKey.getPrivateKey());
final String expiresInIso8601String = new SimpleDateFormat(ISO_8601_DATE_FORMAT).format(new Date(responseToken.getIssuedAt() * 1000L));
final DockerResponse responseEntity = new DockerResponse().setToken(encodedToken).setExpires_in(accessTokenLifespan).setIssued_at(expiresInIso8601String);
return new ResponseBuilderImpl().status(Response.Status.OK).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(responseEntity).build();
} else {
logger.errorv("Unable to handle request for event type {0}. Currently only LOGIN event types are supported by docker protocol.", event.getEvent() == null ? "null" : event.getEvent().getType());
throw new ErrorResponseException("invalid_request", "Event type not supported", Response.Status.BAD_REQUEST);
}
} catch (final InstantiationException e) {
logger.errorv("Error attempting to create Key ID for Docker JOSE header: ", e.getMessage());
throw new ErrorResponseException("token_error", "Unable to construct JOSE header for JWT", Response.Status.INTERNAL_SERVER_ERROR);
}
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class AuthorizationEndpointBase method createAuthenticationSession.
protected AuthenticationSessionModel createAuthenticationSession(ClientModel client, String requestState) {
AuthenticationSessionManager manager = new AuthenticationSessionManager(session);
RootAuthenticationSessionModel rootAuthSession = manager.getCurrentRootAuthenticationSession(realm);
AuthenticationSessionModel authSession;
if (rootAuthSession != null) {
authSession = rootAuthSession.createAuthenticationSession(client);
logger.debugf("Sent request to authz endpoint. Root authentication session with ID '%s' exists. Client is '%s' . Created new authentication session with tab ID: %s", rootAuthSession.getId(), client.getClientId(), authSession.getTabId());
} else {
UserSessionCrossDCManager userSessionCrossDCManager = new UserSessionCrossDCManager(session);
UserSessionModel userSession = userSessionCrossDCManager.getUserSessionIfExistsRemotely(manager, realm);
if (userSession != null) {
UserModel user = userSession.getUser();
if (user != null && !user.isEnabled()) {
authSession = createNewAuthenticationSession(manager, client);
AuthenticationManager.backchannelLogout(session, userSession, true);
} else {
String userSessionId = userSession.getId();
rootAuthSession = session.authenticationSessions().createRootAuthenticationSession(realm, userSessionId);
authSession = rootAuthSession.createAuthenticationSession(client);
logger.debugf("Sent request to authz endpoint. We don't have root authentication session with ID '%s' but we have userSession." + "Re-created root authentication session with same ID. Client is: %s . New authentication session tab ID: %s", userSessionId, client.getClientId(), authSession.getTabId());
}
} else {
authSession = createNewAuthenticationSession(manager, client);
}
}
session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession);
return authSession;
}
use of org.keycloak.models.UserSessionModel 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());
});
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class UserSessionProviderOfflineTest method testOnRealmRemoved.
@Test
@ModelTest
public void testOnRealmRemoved(KeycloakSession session) {
AtomicReference<String> userSessionID = new AtomicReference<>();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR1) -> {
currentSession = sessionRR1;
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.setSsoSessionIdleTimeout(1800);
fooRealm.setSsoSessionMaxLifespan(36000);
fooRealm.setOfflineSessionIdleTimeout(2592000);
fooRealm.setOfflineSessionMaxLifespan(5184000);
fooRealm.addClient("foo-app");
currentSession.users().addUser(fooRealm, "user3");
UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
userSessionID.set(userSession.getId());
createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR2) -> {
currentSession = sessionRR2;
sessionManager = new UserSessionManager(currentSession);
// Persist offline session
RealmModel fooRealm = currentSession.realms().getRealm("foo");
UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
createOfflineSessionIncludeClientSessions(currentSession, userSession);
UserSessionModel offlineUserSession = sessionManager.findOfflineUserSession(fooRealm, userSession.getId());
Assert.assertEquals(offlineUserSession.getAuthenticatedClientSessions().size(), 1);
AuthenticatedClientSessionModel offlineClientSession = offlineUserSession.getAuthenticatedClientSessions().values().iterator().next();
Assert.assertEquals("foo-app", offlineClientSession.getClient().getClientId());
Assert.assertEquals("user3", offlineClientSession.getUserSession().getUser().getUsername());
// Remove realm
RealmManager realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR3) -> {
currentSession = sessionRR3;
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.addClient("foo-app");
currentSession.users().addUser(fooRealm, "user3");
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionRR4) -> {
currentSession = sessionRR4;
RealmModel fooRealm = currentSession.realms().getRealm("foo");
Assert.assertEquals(0, currentSession.sessions().getOfflineSessionsCount(fooRealm, fooRealm.getClientByClientId("foo-app")));
// Cleanup
RealmManager realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
});
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class UserSessionProviderOfflineTest method testOnClientRemoved.
@Test
@ModelTest
public void testOnClientRemoved(KeycloakSession session) {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR) -> {
try {
int started = Time.currentTime();
AtomicReference<String> userSessionID = new AtomicReference<>();
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR1) -> {
currentSession = sessionCR1;
sessionManager = new UserSessionManager(currentSession);
RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
fooRealm.setSsoSessionIdleTimeout(1800);
fooRealm.setSsoSessionMaxLifespan(36000);
fooRealm.setOfflineSessionIdleTimeout(2592000);
fooRealm.setOfflineSessionMaxLifespan(5184000);
fooRealm.addClient("foo-app");
fooRealm.addClient("bar-app");
currentSession.users().addUser(fooRealm, "user3");
UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
userSessionID.set(userSession.getId());
createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
createClientSession(currentSession, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR2) -> {
currentSession = sessionCR2;
// Create offline currentSession
RealmModel fooRealm = currentSession.realms().getRealm("foo");
UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
createOfflineSessionIncludeClientSessions(currentSession, userSession);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR3) -> {
currentSession = sessionCR3;
RealmManager realmMgr = new RealmManager(currentSession);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
// Assert currentSession was persisted with both clientSessions
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
assertSession(offlineSession, currentSession.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app");
// Remove foo-app client
ClientModel client = fooRealm.getClientByClientId("foo-app");
clientMgr.removeClient(fooRealm, client);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR4) -> {
currentSession = sessionCR4;
RealmManager realmMgr = new RealmManager(currentSession);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
// Assert just one bar-app clientSession persisted now
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
Assert.assertEquals(1, offlineSession.getAuthenticatedClientSessions().size());
Assert.assertEquals("bar-app", offlineSession.getAuthenticatedClientSessions().values().iterator().next().getClient().getClientId());
// Remove bar-app client
ClientModel client = fooRealm.getClientByClientId("bar-app");
clientMgr.removeClient(fooRealm, client);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCR5) -> {
currentSession = sessionCR5;
// Assert nothing loaded - userSession was removed as well because it was last userSession
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
Assert.assertEquals(0, offlineSession.getAuthenticatedClientSessions().size());
});
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTearDown) -> {
currentSession = sessionTearDown;
RealmManager realmMgr = new RealmManager(currentSession);
RealmModel fooRealm = realmMgr.getRealm("foo");
UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
// Remove user3
new UserManager(currentSession).removeUser(fooRealm, user3);
// Cleanup
realmMgr = new RealmManager(currentSession);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
});
}
});
}
Aggregations