Search in sources :

Example 36 with AuthenticatedClientSessionModel

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

the class AuthenticationManager method backchannelLogoutAll.

private static BackchannelLogoutResponse backchannelLogoutAll(KeycloakSession session, RealmModel realm, UserSessionModel userSession, AuthenticationSessionModel logoutAuthSession, UriInfo uriInfo, HttpHeaders headers, boolean logoutBroker) {
    BackchannelLogoutResponse backchannelLogoutResponse = new BackchannelLogoutResponse();
    for (AuthenticatedClientSessionModel clientSession : userSession.getAuthenticatedClientSessions().values()) {
        Response clientSessionLogoutResponse = backchannelLogoutClientSession(session, realm, clientSession, logoutAuthSession, uriInfo, headers);
        String backchannelLogoutUrl = OIDCAdvancedConfigWrapper.fromClientModel(clientSession.getClient()).getBackchannelLogoutUrl();
        BackchannelLogoutResponse.DownStreamBackchannelLogoutResponse downStreamBackchannelLogoutResponse = new BackchannelLogoutResponse.DownStreamBackchannelLogoutResponse();
        downStreamBackchannelLogoutResponse.setWithBackchannelLogoutUrl(backchannelLogoutUrl != null);
        if (clientSessionLogoutResponse != null) {
            downStreamBackchannelLogoutResponse.setResponseCode(clientSessionLogoutResponse.getStatus());
        } else {
            downStreamBackchannelLogoutResponse.setResponseCode(null);
        }
        backchannelLogoutResponse.addClientResponses(downStreamBackchannelLogoutResponse);
    }
    if (logoutBroker) {
        String brokerId = userSession.getNote(Details.IDENTITY_PROVIDER);
        if (brokerId != null) {
            IdentityProvider identityProvider = IdentityBrokerService.getIdentityProvider(session, realm, brokerId);
            try {
                identityProvider.backchannelLogout(session, userSession, uriInfo, realm);
            } catch (Exception e) {
                logger.warn("Exception at broker backchannel logout for broker " + brokerId, e);
                backchannelLogoutResponse.setLocalLogoutSucceeded(false);
            }
        }
    }
    return backchannelLogoutResponse;
}
Also used : BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) ErrorResponseException(org.keycloak.services.ErrorResponseException) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) VerificationException(org.keycloak.common.VerificationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 37 with AuthenticatedClientSessionModel

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

the class ResourceAdminManager method logoutClientSessions.

protected Response logoutClientSessions(RealmModel realm, ClientModel resource, List<AuthenticatedClientSessionModel> clientSessions) {
    String managementUrl = getManagementUrl(session, resource);
    if (managementUrl != null) {
        // Key is host, value is list of http sessions for this host
        MultivaluedHashMap<String, String> adapterSessionIds = null;
        List<String> userSessions = new LinkedList<>();
        if (clientSessions != null && clientSessions.size() > 0) {
            adapterSessionIds = new MultivaluedHashMap<String, String>();
            for (AuthenticatedClientSessionModel clientSession : clientSessions) {
                String adapterSessionId = clientSession.getNote(AdapterConstants.CLIENT_SESSION_STATE);
                if (adapterSessionId != null) {
                    String host = clientSession.getNote(AdapterConstants.CLIENT_SESSION_HOST);
                    adapterSessionIds.add(host, adapterSessionId);
                }
                if (clientSession.getUserSession() != null)
                    userSessions.add(clientSession.getUserSession().getId());
            }
        }
        if (adapterSessionIds == null || adapterSessionIds.isEmpty()) {
            logger.debugv("Can't logout {0}: no logged adapter sessions", resource.getClientId());
            return null;
        }
        if (managementUrl.contains(CLIENT_SESSION_HOST_PROPERTY)) {
            // Send logout separately to each host (needed for single-sign-out in cluster for non-distributable apps - KEYCLOAK-748)
            for (Map.Entry<String, List<String>> entry : adapterSessionIds.entrySet()) {
                String host = entry.getKey();
                List<String> sessionIds = entry.getValue();
                String currentHostMgmtUrl = managementUrl.replace(CLIENT_SESSION_HOST_PROPERTY, host);
                sendLogoutRequest(realm, resource, sessionIds, userSessions, 0, currentHostMgmtUrl);
            }
            return Response.ok().build();
        } else {
            // Send single logout request
            List<String> allSessionIds = new ArrayList<String>();
            for (List<String> currentIds : adapterSessionIds.values()) {
                allSessionIds.addAll(currentIds);
            }
            return sendLogoutRequest(realm, resource, allSessionIds, userSessions, 0, managementUrl);
        }
    } else {
        logger.debugv("Can't logout {0}: no management url", resource.getClientId());
        return null;
    }
}
Also used : AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) Map(java.util.Map) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) LinkedList(java.util.LinkedList)

Example 38 with AuthenticatedClientSessionModel

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

the class UserSessionManager method revokeOfflineToken.

public boolean revokeOfflineToken(UserModel user, ClientModel client) {
    RealmModel realm = client.getRealm();
    AtomicBoolean anyRemoved = new AtomicBoolean(false);
    kcSession.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList()).forEach(userSession -> {
        AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
        if (clientSession != null) {
            if (logger.isTraceEnabled()) {
                logger.tracef("Removing existing offline token for user '%s' and client '%s' .", user.getUsername(), client.getClientId());
            }
            clientSession.detachFromUserSession();
            checkOfflineUserSessionHasClientSessions(realm, user, userSession);
            anyRemoved.set(true);
        }
    });
    return anyRemoved.get();
}
Also used : RealmModel(org.keycloak.models.RealmModel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Example 39 with AuthenticatedClientSessionModel

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

the class UserSessionManager method createOrUpdateOfflineSession.

public void createOrUpdateOfflineSession(AuthenticatedClientSessionModel clientSession, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    // Create and persist offline userSession if we don't have one
    UserSessionModel offlineUserSession = kcSession.sessions().getOfflineUserSession(clientSession.getRealm(), userSession.getId());
    if (offlineUserSession == null) {
        offlineUserSession = createOfflineUserSession(user, userSession);
    } else {
        // update lastSessionRefresh but don't need to persist
        offlineUserSession.setLastSessionRefresh(Time.currentTime());
    }
    // Create and persist clientSession
    AuthenticatedClientSessionModel offlineClientSession = offlineUserSession.getAuthenticatedClientSessionByClient(clientSession.getClient().getId());
    if (offlineClientSession == null) {
        createOfflineClientSession(user, clientSession, offlineUserSession);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Example 40 with AuthenticatedClientSessionModel

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

the class OIDCAdvancedRequestParamsTest method processClaimsQueryParam.

// CLAIMS
// included in the session client notes, so custom providers can make use of it
@Test
public void processClaimsQueryParam() throws IOException {
    Map<String, Object> claims = ImmutableMap.of("id_token", ImmutableMap.of("test_claim", ImmutableMap.of("essential", true)));
    String claimsJson = JsonSerialization.writeValueAsString(claims);
    driver.navigate().to(oauth.getLoginFormUrl() + "&" + OIDCLoginProtocol.CLAIMS_PARAM + "=" + claimsJson);
    // need to login so session id can be read from event
    loginPage.assertCurrent();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    String sessionId = loginEvent.getSessionId();
    String clientId = loginEvent.getClientId();
    testingClient.server("test").run(session -> {
        RealmModel realmModel = session.getContext().getRealm();
        String clientUuid = realmModel.getClientByClientId(clientId).getId();
        UserSessionModel userSession = session.sessions().getUserSession(realmModel, sessionId);
        AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().get(clientUuid);
        String claimsInSession = clientSession.getNote(OIDCLoginProtocol.CLAIMS_PARAM);
        assertEquals(claimsJson, claimsInSession);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

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