Search in sources :

Example 51 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class TokenManager method checkTokenValidForIntrospection.

/**
 * Checks if the token is valid. Optionally the session last refresh and client session timestamp
 * are updated if the token was valid. This is used to keep the session alive when long lived tokens are used.
 *
 * @param session
 * @param realm
 * @param token
 * @param updateTimestamps
 * @return
 */
public boolean checkTokenValidForIntrospection(KeycloakSession session, RealmModel realm, AccessToken token, boolean updateTimestamps) {
    ClientModel client = realm.getClientByClientId(token.getIssuedFor());
    if (client == null || !client.isEnabled()) {
        return false;
    }
    try {
        TokenVerifier.createWithoutSignature(token).withChecks(NotBeforeCheck.forModel(client), TokenVerifier.IS_ACTIVE, new TokenRevocationCheck(session)).verify();
    } catch (VerificationException e) {
        logger.debugf("JWT check failed: %s", e.getMessage());
        return false;
    }
    boolean valid = false;
    // Tokens without sessions are considered valid. Signature check and revocation check are sufficient checks for them
    if (token.getSessionState() == null) {
        UserModel user = lookupUserFromStatelessToken(session, realm, token);
        valid = isUserValid(session, realm, token, user);
    } else {
        UserSessionModel userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), false, client.getId());
        if (AuthenticationManager.isSessionValid(realm, userSession)) {
            valid = isUserValid(session, realm, token, userSession.getUser());
        } else {
            userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), true, client.getId());
            if (AuthenticationManager.isOfflineSessionValid(realm, userSession)) {
                valid = isUserValid(session, realm, token, userSession.getUser());
            }
        }
        if (valid && (token.isIssuedBeforeSessionStart(userSession.getStarted()))) {
            valid = false;
        }
        AuthenticatedClientSessionModel clientSession = userSession == null ? null : userSession.getAuthenticatedClientSessionByClient(client.getId());
        if (clientSession != null) {
            if (valid && (token.isIssuedBeforeSessionStart(clientSession.getStarted()))) {
                valid = false;
            }
        }
        String tokenType = token.getType();
        if (realm.isRevokeRefreshToken() && (tokenType.equals(TokenUtil.TOKEN_TYPE_REFRESH) || tokenType.equals(TokenUtil.TOKEN_TYPE_OFFLINE)) && !validateTokenReuseForIntrospection(session, realm, token)) {
            return false;
        }
        if (updateTimestamps && valid) {
            int currentTime = Time.currentTime();
            userSession.setLastSessionRefresh(currentTime);
            if (clientSession != null) {
                clientSession.setTimestamp(currentTime);
            }
        }
    }
    return valid;
}
Also used : UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) VerificationException(org.keycloak.common.VerificationException) UserSessionCrossDCManager(org.keycloak.services.managers.UserSessionCrossDCManager)

Example 52 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionProviderOfflineTest method assertSession.

public static void assertSession(UserSessionModel session, UserModel user, String ipAddress, int started, int lastRefresh, String... clients) {
    assertEquals(user.getId(), session.getUser().getId());
    assertEquals(ipAddress, session.getIpAddress());
    assertEquals(user.getUsername(), session.getLoginUsername());
    assertEquals("form", session.getAuthMethod());
    assertTrue(session.isRememberMe());
    assertTrue((session.getStarted() >= started - 1) && (session.getStarted() <= started + 1));
    assertTrue((session.getLastSessionRefresh() >= lastRefresh - 1) && (session.getLastSessionRefresh() <= lastRefresh + 1));
    String[] actualClients = new String[session.getAuthenticatedClientSessions().size()];
    int i = 0;
    for (Map.Entry<String, AuthenticatedClientSessionModel> entry : session.getAuthenticatedClientSessions().entrySet()) {
        String clientUUID = entry.getKey();
        AuthenticatedClientSessionModel clientSession = entry.getValue();
        Assert.assertEquals(clientUUID, clientSession.getClient().getId());
        actualClients[i] = clientSession.getClient().getClientId();
        i++;
    }
}
Also used : AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) HashMap(java.util.HashMap) Map(java.util.Map)

Example 53 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionProviderOfflineTest method createOfflineSessionIncludeClientSessions.

private static Set<String> createOfflineSessionIncludeClientSessions(KeycloakSession session, UserSessionModel userSession) {
    Set<String> offlineSessions = new HashSet<>();
    UserSessionManager localManager = new UserSessionManager(session);
    for (AuthenticatedClientSessionModel clientSession : userSession.getAuthenticatedClientSessions().values()) {
        localManager.createOrUpdateOfflineSession(clientSession, userSession);
        offlineSessions.add(clientSession.getClient().getId());
    }
    return offlineSessions;
}
Also used : UserSessionManager(org.keycloak.services.managers.UserSessionManager) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) HashSet(java.util.HashSet)

Example 54 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionProviderOfflineTest method createClientSession.

private static AuthenticatedClientSessionModel createClientSession(KeycloakSession sessionParam, ClientModel client, UserSessionModel userSession, String redirect, String state) {
    AuthenticatedClientSessionModel clientSession = sessionParam.sessions().createClientSession(client.getRealm(), client, userSession);
    clientSession.setRedirectUri(redirect);
    if (state != null)
        clientSession.setNote(OIDCLoginProtocol.STATE_PARAM, state);
    return clientSession;
}
Also used : AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Example 55 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class OfflineSessionPersistenceTest method createOfflineClientSession.

private String createOfflineClientSession(String offlineUserSessionId, String clientId) {
    return withRealm(realmId, (session, realm) -> {
        UserSessionModel offlineUserSession = session.sessions().getOfflineUserSession(realm, offlineUserSessionId);
        ClientModel client = session.clients().getClientById(realm, clientId);
        AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, client, offlineUserSession);
        return session.sessions().createOfflineClientSession(clientSession, offlineUserSession).getId();
    });
}
Also used : ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Aggregations

AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)59 UserSessionModel (org.keycloak.models.UserSessionModel)35 RealmModel (org.keycloak.models.RealmModel)25 ClientModel (org.keycloak.models.ClientModel)23 Test (org.junit.Test)16 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)13 UserModel (org.keycloak.models.UserModel)12 KeycloakSession (org.keycloak.models.KeycloakSession)11 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)11 HashMap (java.util.HashMap)10 Map (java.util.Map)9 ClientSessionContext (org.keycloak.models.ClientSessionContext)9 LinkedList (java.util.LinkedList)8 DefaultClientSessionContext (org.keycloak.services.util.DefaultClientSessionContext)8 OAuthErrorException (org.keycloak.OAuthErrorException)6 VerificationException (org.keycloak.common.VerificationException)6 AccessToken (org.keycloak.representations.AccessToken)6 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)6 HashSet (java.util.HashSet)5 List (java.util.List)5