Search in sources :

Example 11 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class DeviceEndpoint method createAuthenticationSession.

protected AuthenticationSessionModel createAuthenticationSession(ClientModel client, String scope) {
    AuthenticationSessionModel authenticationSession = super.createAuthenticationSession(client, null);
    authenticationSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    authenticationSession.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name());
    authenticationSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
    if (scope != null)
        authenticationSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scope);
    return authenticationSession;
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel)

Example 12 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class LoginFormsUtil method filterIdentityProviders.

public static List<IdentityProviderModel> filterIdentityProviders(Stream<IdentityProviderModel> providers, KeycloakSession session, AuthenticationFlowContext context) {
    if (context != null) {
        AuthenticationSessionModel authSession = context.getAuthenticationSession();
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        final IdentityProviderModel existingIdp = (serializedCtx == null) ? null : serializedCtx.deserialize(session, authSession).getIdpConfig();
        final Set<String> federatedIdentities;
        if (context.getUser() != null) {
            federatedIdentities = session.users().getFederatedIdentitiesStream(session.getContext().getRealm(), context.getUser()).map(federatedIdentityModel -> federatedIdentityModel.getIdentityProvider()).collect(Collectors.toSet());
        } else {
            federatedIdentities = null;
        }
        return providers.filter(p -> {
            // Filter current IDP during first-broker-login flow. Re-authentication with the "linked" broker should not be possible
            if (existingIdp == null)
                return true;
            return !Objects.equals(p.getAlias(), existingIdp.getAlias());
        }).filter(idp -> {
            // In case that we already have user established in authentication session, we show just providers already linked to this user
            if (federatedIdentities == null)
                return true;
            return federatedIdentities.contains(idp.getAlias());
        }).collect(Collectors.toList());
    }
    return providers.collect(Collectors.toList());
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) AbstractIdpAuthenticator(org.keycloak.authentication.authenticators.broker.AbstractIdpAuthenticator) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) Collectors(java.util.stream.Collectors) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Objects(java.util.Objects) List(java.util.List) UserModel(org.keycloak.models.UserModel) Stream(java.util.stream.Stream) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) Map(java.util.Map) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) AuthenticationFlowContext(org.keycloak.authentication.AuthenticationFlowContext) LinkedList(java.util.LinkedList) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) IdentityProviderModel(org.keycloak.models.IdentityProviderModel)

Example 13 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class AuthenticationManager method backchannelLogout.

/**
 * @param session
 * @param realm
 * @param userSession
 * @param uriInfo
 * @param connection
 * @param headers
 * @param logoutBroker
 * @param offlineSession
 *
 * @return BackchannelLogoutResponse with logout information
 */
public static BackchannelLogoutResponse backchannelLogout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers, boolean logoutBroker, boolean offlineSession) {
    BackchannelLogoutResponse backchannelLogoutResponse = new BackchannelLogoutResponse();
    if (userSession == null) {
        backchannelLogoutResponse.setLocalLogoutSucceeded(true);
        return backchannelLogoutResponse;
    }
    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());
    boolean expireUserSessionCookieSucceeded = expireUserSessionCookie(session, userSession, realm, uriInfo, headers, connection);
    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, false);
    boolean userSessionOnlyHasLoggedOutClients = false;
    try {
        backchannelLogoutResponse = backchannelLogoutAll(session, realm, userSession, logoutAuthSession, uriInfo, headers, logoutBroker);
        userSessionOnlyHasLoggedOutClients = 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
        String onlineUserSessionId = userSession.getNote(CORRESPONDING_SESSION_ID);
        UserSessionModel onlineUserSession = (onlineUserSessionId != null) ? session.sessions().getUserSession(realm, onlineUserSessionId) : session.sessions().getUserSession(realm, userSession.getId());
        if (onlineUserSession != null) {
            session.sessions().removeUserSession(realm, onlineUserSession);
        }
    } else {
        session.sessions().removeUserSession(realm, userSession);
    }
    backchannelLogoutResponse.setLocalLogoutSucceeded(expireUserSessionCookieSucceeded && userSessionOnlyHasLoggedOutClients);
    return backchannelLogoutResponse;
}
Also used : UserModel(org.keycloak.models.UserModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse)

Example 14 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class AuthenticationManager method browserLogoutAllClients.

private static Response browserLogoutAllClients(UserSessionModel userSession, KeycloakSession session, RealmModel realm, HttpHeaders headers, UriInfo uriInfo, AuthenticationSessionModel logoutAuthSession) {
    Map<Boolean, List<AuthenticatedClientSessionModel>> acss = userSession.getAuthenticatedClientSessions().values().stream().filter(clientSession -> !Objects.equals(AuthenticationSessionModel.Action.LOGGED_OUT.name(), clientSession.getAction()) && !Objects.equals(AuthenticationSessionModel.Action.LOGGING_OUT.name(), clientSession.getAction())).filter(clientSession -> clientSession.getProtocol() != null).collect(Collectors.partitioningBy(clientSession -> clientSession.getClient().isFrontchannelLogout()));
    final List<AuthenticatedClientSessionModel> backendLogoutSessions = acss.get(false) == null ? Collections.emptyList() : acss.get(false);
    backendLogoutSessions.forEach(acs -> backchannelLogoutClientSession(session, realm, acs, logoutAuthSession, uriInfo, headers));
    final List<AuthenticatedClientSessionModel> redirectClients = acss.get(true) == null ? Collections.emptyList() : acss.get(true);
    for (AuthenticatedClientSessionModel nextRedirectClient : redirectClients) {
        Response response = frontchannelLogoutClientSession(session, realm, nextRedirectClient, logoutAuthSession, uriInfo, headers);
        if (response != null) {
            return response;
        }
    }
    return null;
}
Also used : DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ActionTokenStoreProvider(org.keycloak.models.ActionTokenStoreProvider) Error(org.keycloak.protocol.LoginProtocol.Error) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) UriBuilder(javax.ws.rs.core.UriBuilder) Time(org.keycloak.common.util.Time) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) Set(java.util.Set) AbstractUsernameFormAuthenticator(org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator) SecretGenerator(org.keycloak.common.util.SecretGenerator) Stream(java.util.stream.Stream) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) SessionTimeoutHelper(org.keycloak.models.utils.SessionTimeoutHelper) LoginActionsService(org.keycloak.services.resources.LoginActionsService) UriInfo(javax.ws.rs.core.UriInfo) OAuth2Constants(org.keycloak.OAuth2Constants) LoginProtocol(org.keycloak.protocol.LoginProtocol) Constants(org.keycloak.models.Constants) TokenManager(org.keycloak.protocol.oidc.TokenManager) TokenUtil(org.keycloak.util.TokenUtil) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) Predicate(org.keycloak.TokenVerifier.Predicate) TokenVerifier(org.keycloak.TokenVerifier) CommonClientSessionModel(org.keycloak.sessions.CommonClientSessionModel) Base64Url(org.keycloak.common.util.Base64Url) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) AuthenticationFlowError(org.keycloak.authentication.AuthenticationFlowError) ConsoleDisplayMode(org.keycloak.authentication.ConsoleDisplayMode) IdentityBrokerService(org.keycloak.services.resources.IdentityBrokerService) KeycloakSession(org.keycloak.models.KeycloakSession) AuthorizationDetails(org.keycloak.rar.AuthorizationDetails) HttpRequest(org.jboss.resteasy.spi.HttpRequest) EventType(org.keycloak.events.EventType) P3PHelper(org.keycloak.services.util.P3PHelper) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) URLDecoder(java.net.URLDecoder) ActionTokenKeyModel(org.keycloak.models.ActionTokenKeyModel) RequiredActionContextResult(org.keycloak.authentication.RequiredActionContextResult) RequiredActionFactory(org.keycloak.authentication.RequiredActionFactory) NewCookie(javax.ws.rs.core.NewCookie) Messages(org.keycloak.services.messages.Messages) DefaultActionTokenKey(org.keycloak.authentication.actiontoken.DefaultActionTokenKey) SignatureVerifierContext(org.keycloak.crypto.SignatureVerifierContext) AccessToken(org.keycloak.representations.AccessToken) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) URI(java.net.URI) SystemClientUtil(org.keycloak.models.utils.SystemClientUtil) VerificationException(org.keycloak.common.VerificationException) DeviceGrantType.isOAuth2DeviceVerificationFlow(org.keycloak.protocol.oidc.grants.device.DeviceGrantType.isOAuth2DeviceVerificationFlow) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) InitiatedActionSupport(org.keycloak.authentication.InitiatedActionSupport) AuthenticatorUtil(org.keycloak.authentication.AuthenticatorUtil) Collectors(java.util.stream.Collectors) Cookie(javax.ws.rs.core.Cookie) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) ClientModel(org.keycloak.models.ClientModel) RealmsResource(org.keycloak.services.resources.RealmsResource) Profile(org.keycloak.common.Profile) SameSiteAttributeValue(org.keycloak.common.util.ServerCookie.SameSiteAttributeValue) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) ServicesLogger(org.keycloak.services.ServicesLogger) TokenTypeCheck(org.keycloak.TokenVerifier.TokenTypeCheck) RequiredActionContext(org.keycloak.authentication.RequiredActionContext) SignatureProvider(org.keycloak.crypto.SignatureProvider) EventBuilder(org.keycloak.events.EventBuilder) CookieHelper(org.keycloak.services.util.CookieHelper) UserConsentModel(org.keycloak.models.UserConsentModel) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) LinkedList(java.util.LinkedList) DisplayTypeRequiredActionFactory(org.keycloak.authentication.DisplayTypeRequiredActionFactory) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) Errors(org.keycloak.events.Errors) CORRESPONDING_SESSION_ID(org.keycloak.models.UserSessionModel.CORRESPONDING_SESSION_ID) UserSessionModel(org.keycloak.models.UserSessionModel) AuthorizationContextUtil(org.keycloak.services.util.AuthorizationContextUtil) URLEncoder(java.net.URLEncoder) LogoutRequestContext(org.keycloak.services.clientpolicy.context.LogoutRequestContext) CookieHelper.getCookie(org.keycloak.services.util.CookieHelper.getCookie) Urls(org.keycloak.services.Urls) Collections(java.util.Collections) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) List(java.util.List) LinkedList(java.util.LinkedList)

Example 15 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class AuthenticationManager method browserLogout.

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);
}
Also used : UserModel(org.keycloak.models.UserModel) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) IdentityProvider(org.keycloak.broker.provider.IdentityProvider)

Aggregations

AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)89 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)48 ClientModel (org.keycloak.models.ClientModel)27 UserModel (org.keycloak.models.UserModel)24 Response (javax.ws.rs.core.Response)23 RealmModel (org.keycloak.models.RealmModel)20 UserSessionModel (org.keycloak.models.UserSessionModel)20 AuthenticationSessionManager (org.keycloak.services.managers.AuthenticationSessionManager)18 KeycloakSession (org.keycloak.models.KeycloakSession)16 ClientSessionContext (org.keycloak.models.ClientSessionContext)13 LoginFormsProvider (org.keycloak.forms.login.LoginFormsProvider)10 URI (java.net.URI)9 UriBuilder (javax.ws.rs.core.UriBuilder)9 EventBuilder (org.keycloak.events.EventBuilder)9 LoginProtocol (org.keycloak.protocol.LoginProtocol)9 GET (javax.ws.rs.GET)8 Path (javax.ws.rs.Path)8 AuthenticationFlowException (org.keycloak.authentication.AuthenticationFlowException)8 OIDCLoginProtocol (org.keycloak.protocol.oidc.OIDCLoginProtocol)8 Map (java.util.Map)7