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

The following examples show how to use org.keycloak.models.UserSessionModel#isRememberMe() . 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 boolean isSessionValid(RealmModel realm, UserSessionModel userSession) {
    if (userSession == null) {
        logger.debug("No user session");
        return false;
    }
    int currentTime = Time.currentTime();

    // Additional time window is added for the case when session was updated in different DC and the update to current DC was postponed
    int maxIdle = userSession.isRememberMe() && realm.getSsoSessionIdleTimeoutRememberMe() > 0 ?
        realm.getSsoSessionIdleTimeoutRememberMe() : realm.getSsoSessionIdleTimeout();
    int maxLifespan = userSession.isRememberMe() && realm.getSsoSessionMaxLifespanRememberMe() > 0 ?
            realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan();

    boolean sessionIdleOk = maxIdle > currentTime - userSession.getLastSessionRefresh() - SessionTimeoutHelper.IDLE_TIMEOUT_WINDOW_SECONDS;
    boolean sessionMaxOk = maxLifespan > currentTime - userSession.getStarted();
    return sessionIdleOk && sessionMaxOk;
}
 
Example 2
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createLoginCookie(KeycloakSession keycloakSession, RealmModel realm, UserModel user, UserSessionModel session, UriInfo uriInfo, ClientConnection connection) {
    String cookiePath = getIdentityCookiePath(realm, uriInfo);
    String issuer = Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName());
    IdentityCookieToken identityCookieToken = createIdentityToken(keycloakSession, realm, user, session, issuer);
    String encoded = keycloakSession.tokens().encode(identityCookieToken);
    boolean secureOnly = realm.getSslRequired().isRequired(connection);
    int maxAge = NewCookie.DEFAULT_MAX_AGE;
    if (session != null && session.isRememberMe()) {
        maxAge = realm.getSsoSessionMaxLifespanRememberMe() > 0 ? realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan();
    }
    logger.debugv("Create login cookie - name: {0}, path: {1}, max-age: {2}", KEYCLOAK_IDENTITY_COOKIE, cookiePath, maxAge);
    CookieHelper.addCookie(KEYCLOAK_IDENTITY_COOKIE, encoded, cookiePath, null, null, maxAge, secureOnly, true, SameSiteAttributeValue.NONE);
    //builder.cookie(new NewCookie(cookieName, encoded, cookiePath, null, null, maxAge, secureOnly));// todo httponly , true);

    String sessionCookieValue = realm.getName() + "/" + user.getId();
    if (session != null) {
        sessionCookieValue += "/" + session.getId();
    }
    // THIS SHOULD NOT BE A HTTPONLY COOKIE!  It is used for OpenID Connect Iframe Session support!
    // Max age should be set to the max lifespan of the session as it's used to invalidate old-sessions on re-login
    int sessionCookieMaxAge = session.isRememberMe() && realm.getSsoSessionMaxLifespanRememberMe() > 0 ? realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan();
    CookieHelper.addCookie(KEYCLOAK_SESSION_COOKIE, sessionCookieValue, cookiePath, null, null, sessionCookieMaxAge, secureOnly, false, SameSiteAttributeValue.NONE);
    P3PHelper.addP3PHeader();
}
 
Example 3
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static IdentityCookieToken createIdentityToken(KeycloakSession keycloakSession, RealmModel realm, UserModel user, UserSessionModel session, String issuer) {
    IdentityCookieToken token = new IdentityCookieToken();
    token.id(KeycloakModelUtils.generateId());
    token.issuedNow();
    token.subject(user.getId());
    token.issuer(issuer);
    token.type(TokenUtil.TOKEN_TYPE_KEYCLOAK_ID);

    if (session != null) {
        token.setSessionState(session.getId());
    }

    if (session != null && session.isRememberMe() && realm.getSsoSessionMaxLifespanRememberMe() > 0) {
        token.expiration(Time.currentTime() + realm.getSsoSessionMaxLifespanRememberMe());
    } else if (realm.getSsoSessionMaxLifespan() > 0) {
        token.expiration(Time.currentTime() + realm.getSsoSessionMaxLifespan());
    }

    String stateChecker = (String) keycloakSession.getAttribute("state_checker");
    if (stateChecker == null) {
        stateChecker = Base64Url.encode(KeycloakModelUtils.generateSecret());
        keycloakSession.setAttribute("state_checker", stateChecker);
    }
    token.getOtherClaims().put("state_checker", stateChecker);

    return token;
}
 
Example 4
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);

}