use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class CacheTest method testAddUserNotAddedToCache.
@Test
public void testAddUserNotAddedToCache() {
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealmByName("test");
UserModel user = session.users().addUser(realm, "testAddUserNotAddedToCache");
user.setFirstName("firstName");
user.addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP);
UserSessionModel userSession = session.sessions().createUserSession(UUID.randomUUID().toString(), realm, user, "testAddUserNotAddedToCache", "127.0.0.1", "auth", false, null, null, UserSessionModel.SessionPersistenceState.PERSISTENT);
user = userSession.getUser();
user.setLastName("lastName");
assertNotNull(user.getLastName());
});
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class DeviceActivityTest method timesTests.
@Test
public void timesTests() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy, h:mm a", Locale.ENGLISH);
LocalDateTime now = LocalDateTime.now();
LocalDateTime nowPlus1 = now.plusMinutes(1);
String nowStr = now.format(formatter);
String nowStrPlus1 = nowPlus1.format(formatter);
String sessionId = createSession(Browsers.CHROME);
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealmByName(TEST);
UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
userSession.setLastSessionRefresh(Time.currentTime() + 120);
});
deviceActivityPage.clickRefreshPage();
DeviceActivityPage.Session session = deviceActivityPage.getSession(sessionId);
String startedAtStr = session.getStarted();
LocalDateTime startedAt = LocalDateTime.parse(startedAtStr, formatter);
LocalDateTime lastAccessed = LocalDateTime.parse(session.getLastAccess(), formatter);
LocalDateTime expiresAt = LocalDateTime.parse(session.getExpires(), formatter);
assertTrue("Last access should be after started at", lastAccessed.isAfter(startedAt));
assertTrue("Expires at should be after last access", expiresAt.isAfter(lastAccessed));
assertTrue("Last accessed should be in the future", lastAccessed.isAfter(now));
assertThat(startedAtStr, either(equalTo(nowStr)).or(equalTo(nowStrPlus1)));
int ssoLifespan = testRealmResource().toRepresentation().getSsoSessionMaxLifespan();
assertEquals(startedAt.plusSeconds(ssoLifespan), expiresAt);
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class LoginActionsServiceChecks method checkNotLoggedInYet.
/**
* Verifies that the authentication session has not yet been converted to user session, in other words
* that the user has not yet completed authentication and logged in.
*/
public static <T extends JsonWebToken> void checkNotLoggedInYet(ActionTokenContext<T> context, AuthenticationSessionModel authSessionFromCookie, String authSessionId) throws VerificationException {
if (authSessionId == null) {
return;
}
UserSessionModel userSession = context.getSession().sessions().getUserSession(context.getRealm(), authSessionId);
boolean hasNoRequiredActions = (userSession == null || userSession.getUser().getRequiredActionsStream().count() == 0) && (authSessionFromCookie == null || authSessionFromCookie.getRequiredActions() == null || authSessionFromCookie.getRequiredActions().isEmpty());
if (userSession != null && hasNoRequiredActions) {
LoginFormsProvider loginForm = context.getSession().getProvider(LoginFormsProvider.class).setAuthenticationSession(context.getAuthenticationSession()).setSuccess(Messages.ALREADY_LOGGED_IN);
if (context.getSession().getContext().getClient() == null) {
loginForm.setAttribute(Constants.SKIP_LINK, true);
}
throw new LoginActionsServiceException(loginForm.createInfoPage());
}
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class SessionCodeChecks method initialVerifyAuthSession.
public AuthenticationSessionModel initialVerifyAuthSession() {
// Basic realm checks
if (!checkSsl()) {
event.error(Errors.SSL_REQUIRED);
response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
return null;
}
if (!realm.isEnabled()) {
event.error(Errors.REALM_DISABLED);
response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
return null;
}
// Setup client to be shown on error/info page based on "client_id" parameter
logger.debugf("Will use client '%s' in back-to-application link", clientId);
ClientModel client = null;
if (clientId != null) {
client = realm.getClientByClientId(clientId);
}
if (client != null) {
session.getContext().setClient(client);
}
// object retrieve
AuthenticationSessionManager authSessionManager = new AuthenticationSessionManager(session);
AuthenticationSessionModel authSession = null;
if (authSessionId != null)
authSession = authSessionManager.getAuthenticationSessionByIdAndClient(realm, authSessionId, client, tabId);
AuthenticationSessionModel authSessionCookie = authSessionManager.getCurrentAuthenticationSession(realm, client, tabId);
if (authSession != null && authSessionCookie != null && !authSession.getParentSession().getId().equals(authSessionCookie.getParentSession().getId())) {
event.detail(Details.REASON, "cookie does not match auth_session query parameter");
event.error(Errors.INVALID_CODE);
response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
return null;
}
if (authSession != null) {
session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession);
return authSession;
}
if (authSessionCookie != null) {
session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSessionCookie);
return authSessionCookie;
}
// See if we are already authenticated and userSession with same ID exists.
UserSessionModel userSession = authSessionManager.getUserSessionFromAuthCookie(realm);
if (userSession != null) {
LoginFormsProvider loginForm = session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.ALREADY_LOGGED_IN);
if (client == null) {
loginForm.setAttribute(Constants.SKIP_LINK, true);
}
response = loginForm.createInfoPage();
return null;
}
// Otherwise just try to restart from the cookie
RootAuthenticationSessionModel existingRootAuthSession = authSessionManager.getCurrentRootAuthenticationSession(realm);
response = restartAuthenticationSessionFromCookie(existingRootAuthSession);
return null;
}
use of org.keycloak.models.UserSessionModel in project keycloak by keycloak.
the class LoginActionsService method restartSession.
/**
* protocol independent page for restart of the flow
*
* @return
*/
@Path(RESTART_PATH)
@GET
public // optional, can get from cookie instead
Response restartSession(// optional, can get from cookie instead
@QueryParam(AUTH_SESSION_ID) String authSessionId, @QueryParam(Constants.CLIENT_ID) String clientId, @QueryParam(Constants.TAB_ID) String tabId) {
event.event(EventType.RESTART_AUTHENTICATION);
SessionCodeChecks checks = new SessionCodeChecks(realm, session.getContext().getUri(), request, clientConnection, session, event, authSessionId, null, null, clientId, tabId, null);
AuthenticationSessionModel authSession = checks.initialVerifyAuthSession();
if (authSession == null) {
return checks.getResponse();
}
String flowPath = authSession.getClientNote(AuthorizationEndpointBase.APP_INITIATED_FLOW);
if (flowPath == null) {
flowPath = AUTHENTICATE_PATH;
}
// See if we already have userSession attached to authentication session. This means restart of authentication session during re-authentication
// We logout userSession in this case
UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authSession);
if (userSession != null) {
logger.debugf("Logout of user session %s when restarting flow during re-authentication", userSession.getId());
AuthenticationManager.backchannelLogout(session, userSession, false);
}
AuthenticationProcessor.resetFlow(authSession, flowPath);
URI redirectUri = getLastExecutionUrl(flowPath, null, authSession.getClient().getClientId(), tabId);
logger.debugf("Flow restart requested. Redirecting to %s", redirectUri);
return Response.status(Response.Status.FOUND).location(redirectUri).build();
}
Aggregations