Java Code Examples for org.keycloak.models.UserSessionModel#setState()

The following examples show how to use org.keycloak.models.UserSessionModel#setState() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static Response finishBrowserLogout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers) {
    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true);

    checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);

    expireIdentityCookie(realm, uriInfo, connection);
    expireRememberMeCookie(realm, uriInfo, connection);
    userSession.setState(UserSessionModel.State.LOGGED_OUT);
    String method = userSession.getNote(KEYCLOAK_LOGOUT_PROTOCOL);
    EventBuilder event = new EventBuilder(realm, session, connection);
    LoginProtocol protocol = session.getProvider(LoginProtocol.class, method);
    protocol.setRealm(realm)
            .setHttpHeaders(headers)
            .setUriInfo(uriInfo)
            .setEventBuilder(event);
    Response response = protocol.finishLogout(userSession);
    session.sessions().removeUserSession(realm, userSession);
    session.authenticationSessions().removeRootAuthenticationSession(realm, logoutAuthSession.getParentSession());
    return response;
}
 
Example 2
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param session
 * @param realm
 * @param userSession
 * @param uriInfo
 * @param connection
 * @param headers
 * @param logoutBroker
 * @param offlineSession
 */
public static void backchannelLogout(KeycloakSession session, RealmModel realm,
                                     UserSessionModel userSession, UriInfo uriInfo,
                                     ClientConnection connection, HttpHeaders headers,
                                     boolean logoutBroker,
                                     boolean offlineSession) {
    if (userSession == null) return;
    UserModel user = userSession.getUser();
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }

    logger.debugv("Logging out: {0} ({1}) offline: {2}", user.getUsername(), userSession.getId(), userSession.isOffline());
    expireUserSessionCookie(session, userSession, realm, uriInfo, headers, connection);

    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, false);

    try {
        backchannelLogoutAll(session, realm, userSession, logoutAuthSession, uriInfo, headers, logoutBroker);
        checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);
    } finally {
        RootAuthenticationSessionModel rootAuthSession = logoutAuthSession.getParentSession();
        rootAuthSession.removeAuthenticationSessionByTabId(logoutAuthSession.getTabId());
    }

    userSession.setState(UserSessionModel.State.LOGGED_OUT);

    if (offlineSession) {
        new UserSessionManager(session).revokeOfflineUserSession(userSession);

        // Check if "online" session still exists and remove it too
        UserSessionModel onlineUserSession = session.sessions().getUserSession(realm, userSession.getId());
        if (onlineUserSession != null) {
            session.sessions().removeUserSession(realm, onlineUserSession);
        }
    } else {
        session.sessions().removeUserSession(realm, userSession);
    }
}
 
Example 3
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response browserLogout(KeycloakSession session,
                                     RealmModel realm,
                                     UserSessionModel userSession,
                                     UriInfo uriInfo,
                                     ClientConnection connection,
                                     HttpHeaders headers,
                                     String initiatingIdp) {
    if (userSession == null) return null;

    if (logger.isDebugEnabled()) {
        UserModel user = userSession.getUser();
        logger.debugv("Logging out: {0} ({1})", user.getUsername(), userSession.getId());
    }
    
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }

    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true);

    Response response = browserLogoutAllClients(userSession, session, realm, headers, uriInfo, logoutAuthSession);
    if (response != null) {
        return response;
    }

    String brokerId = userSession.getNote(Details.IDENTITY_PROVIDER);
    if (brokerId != null && !brokerId.equals(initiatingIdp)) {
        IdentityProvider identityProvider = IdentityBrokerService.getIdentityProvider(session, realm, brokerId);
        response = identityProvider.keycloakInitiatedBrowserLogout(session, userSession, uriInfo, realm);
        if (response != null) {
            return response;
        }
    }

    return finishBrowserLogout(session, realm, userSession, uriInfo, connection, headers);
}
 
Example 4
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static ClientSessionContext attachSession(AuthenticationSessionModel authSession, UserSessionModel userSession, KeycloakSession session, RealmModel realm, ClientConnection connection, EventBuilder event) {
    String username = authSession.getAuthenticatedUser().getUsername();
    String attemptedUsername = authSession.getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);
    if (attemptedUsername != null) username = attemptedUsername;
    String rememberMe = authSession.getAuthNote(Details.REMEMBER_ME);
    boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("true");
    String brokerSessionId = authSession.getAuthNote(BROKER_SESSION_ID);
    String brokerUserId = authSession.getAuthNote(BROKER_USER_ID);

    if (userSession == null) { // if no authenticator attached a usersession

        userSession = session.sessions().getUserSession(realm, authSession.getParentSession().getId());
        if (userSession == null) {
            userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, authSession.getAuthenticatedUser(), username, connection.getRemoteAddr(), authSession.getProtocol()
                    , remember, brokerSessionId, brokerUserId);
        } else if (userSession.getUser() == null || !AuthenticationManager.isSessionValid(realm, userSession)) {
            userSession.restartSession(realm, authSession.getAuthenticatedUser(), username, connection.getRemoteAddr(), authSession.getProtocol()
                    , remember, brokerSessionId, brokerUserId);
        } else {
            // We have existing userSession even if it wasn't attached to authenticator. Could happen if SSO authentication was ignored (eg. prompt=login) and in some other cases.
            // We need to handle case when different user was used
            logger.debugf("No SSO login, but found existing userSession with ID '%s' after finished authentication.", userSession.getId());
            if (!authSession.getAuthenticatedUser().equals(userSession.getUser())) {
                event.detail(Details.EXISTING_USER, userSession.getUser().getId());
                event.error(Errors.DIFFERENT_USER_AUTHENTICATED);
                throw new ErrorPageException(session, authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.DIFFERENT_USER_AUTHENTICATED, userSession.getUser().getUsername());
            }
        }
        userSession.setState(UserSessionModel.State.LOGGED_IN);
    }

    if (remember) {
        event.detail(Details.REMEMBER_ME, "true");
    }

    ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);

    event.user(userSession.getUser())
            .detail(Details.USERNAME, username)
            .session(userSession);

    return clientSessionCtx;
}
 
Example 5
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static Response redirectAfterSuccessfulFlow(KeycloakSession session, RealmModel realm, UserSessionModel userSession,
                                                   ClientSessionContext clientSessionCtx,
                                                   HttpRequest request, UriInfo uriInfo, ClientConnection clientConnection,
                                                   EventBuilder event, AuthenticationSessionModel authSession, LoginProtocol protocol) {
    Cookie sessionCookie = getCookie(request.getHttpHeaders().getCookies(), AuthenticationManager.KEYCLOAK_SESSION_COOKIE);
    if (sessionCookie != null) {

        String[] split = sessionCookie.getValue().split("/");
        if (split.length >= 3) {
            String oldSessionId = split[2];
            if (!oldSessionId.equals(userSession.getId())) {
                UserSessionModel oldSession = session.sessions().getUserSession(realm, oldSessionId);
                if (oldSession != null) {
                    logger.debugv("Removing old user session: session: {0}", oldSessionId);
                    session.sessions().removeUserSession(realm, oldSession);
                }
            }
        }
    }

    // Updates users locale if required
    session.getContext().resolveLocale(userSession.getUser());

    // refresh the cookies!
    createLoginCookie(session, realm, userSession.getUser(), userSession, uriInfo, clientConnection);
    if (userSession.getState() != UserSessionModel.State.LOGGED_IN) userSession.setState(UserSessionModel.State.LOGGED_IN);
    if (userSession.isRememberMe()) {
        createRememberMeCookie(realm, userSession.getLoginUsername(), uriInfo, clientConnection);
    } else {
        expireRememberMeCookie(realm, uriInfo, clientConnection);
    }

    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();

    // Update userSession note with authTime. But just if flag SSO_AUTH is not set
    boolean isSSOAuthentication = "true".equals(session.getAttribute(SSO_AUTH));
    if (isSSOAuthentication) {
        clientSession.setNote(SSO_AUTH, "true");
    } else {
        int authTime = Time.currentTime();
        userSession.setNote(AUTH_TIME, String.valueOf(authTime));
        clientSession.removeNote(SSO_AUTH);
    }

    // The user has successfully logged in and we can clear his/her previous login failure attempts.
    logSuccess(session, authSession);

    return protocol.authenticated(authSession, userSession, clientSessionCtx);

}