Search in sources :

Example 16 with AuthenticationSessionModel

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

the class AuthenticationManager method frontchannelLogoutClientSession.

private static Response frontchannelLogoutClientSession(KeycloakSession session, RealmModel realm, AuthenticatedClientSessionModel clientSession, AuthenticationSessionModel logoutAuthSession, UriInfo uriInfo, HttpHeaders headers) {
    UserSessionModel userSession = clientSession.getUserSession();
    ClientModel client = clientSession.getClient();
    if (!client.isFrontchannelLogout() || AuthenticationSessionModel.Action.LOGGED_OUT.name().equals(clientSession.getAction())) {
        return null;
    }
    final AuthenticationSessionModel.Action logoutState = getClientLogoutAction(logoutAuthSession, client.getId());
    if (logoutState == AuthenticationSessionModel.Action.LOGGED_OUT || logoutState == AuthenticationSessionModel.Action.LOGGING_OUT) {
        return null;
    }
    try {
        session.clientPolicy().triggerOnEvent(new LogoutRequestContext());
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
    }
    try {
        setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGING_OUT);
        String authMethod = clientSession.getProtocol();
        // must be a keycloak service like account
        if (authMethod == null)
            return null;
        logger.debugv("frontchannel logout to: {0}", client.getClientId());
        LoginProtocol protocol = session.getProvider(LoginProtocol.class, authMethod);
        protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(uriInfo);
        Response response = protocol.frontchannelLogout(userSession, clientSession);
        if (response != null) {
            logger.debug("returning frontchannel logout request to client");
            if (!AuthenticationSessionModel.Action.LOGGING_OUT.name().equals(clientSession.getAction())) {
                setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGED_OUT);
            }
            return response;
        }
    } catch (Exception e) {
        ServicesLogger.LOGGER.failedToLogoutClient(e);
    }
    return null;
}
Also used : BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) LogoutRequestContext(org.keycloak.services.clientpolicy.context.LogoutRequestContext) LoginProtocol(org.keycloak.protocol.LoginProtocol) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) 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) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException)

Example 17 with AuthenticationSessionModel

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

the class ConditionalLoaAuthenticator method matchCondition.

@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    int currentLoa = AuthenticatorUtil.getCurrentLevelOfAuthentication(authSession);
    int requestedLoa = AuthenticatorUtil.getRequestedLevelOfAuthentication(authSession);
    Integer configuredLoa = getConfiguredLoa(context);
    boolean result = (currentLoa < Constants.MINIMUM_LOA && requestedLoa < Constants.MINIMUM_LOA) || ((configuredLoa == null || currentLoa < configuredLoa) && currentLoa < requestedLoa);
    logger.tracef("Checking condition '%s' : currentLoa: %d, requestedLoa: %d, configuredLoa: %d, evaluation result: %b", context.getAuthenticatorConfig().getAlias(), currentLoa, requestedLoa, configuredLoa, result);
    return result;
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel)

Example 18 with AuthenticationSessionModel

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

the class SamlService method idpInitiatedSSO.

@GET
@Path("clients/{client}")
@Produces(MediaType.TEXT_HTML_UTF_8)
public Response idpInitiatedSSO(@PathParam("client") String clientUrlName, @QueryParam("RelayState") String relayState) {
    event.event(EventType.LOGIN);
    CacheControlUtil.noBackButtonCacheControlHeader();
    ClientModel client = session.clients().searchClientsByAttributes(realm, Collections.singletonMap(SamlProtocol.SAML_IDP_INITIATED_SSO_URL_NAME, clientUrlName), 0, 1).findFirst().orElse(null);
    if (client == null) {
        event.error(Errors.CLIENT_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND);
    }
    if (!client.isEnabled()) {
        event.error(Errors.CLIENT_DISABLED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.CLIENT_DISABLED);
    }
    if (!isClientProtocolCorrect(client)) {
        event.error(Errors.INVALID_CLIENT);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, "Wrong client protocol.");
    }
    session.getContext().setClient(client);
    AuthenticationSessionModel authSession = getOrCreateLoginSessionForIdpInitiatedSso(this.session, this.realm, client, relayState);
    if (authSession == null) {
        logger.error("SAML assertion consumer url not set up");
        event.error(Errors.INVALID_REDIRECT_URI);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
    }
    return newBrowserAuthentication(authSession, false, false);
}
Also used : ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 19 with AuthenticationSessionModel

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

the class SamlService method getOrCreateLoginSessionForIdpInitiatedSso.

/**
 * Creates a client session object for SAML IdP-initiated SSO session.
 * The session takes the parameters from from client definition,
 * namely binding type and redirect URL.
 *
 * @param session KC session
 * @param realm Realm to create client session in
 * @param client Client to create client session for
 * @param relayState Optional relay state - free field as per SAML specification
 * @return The auth session model or null if there is no SAML url is found
 */
public AuthenticationSessionModel getOrCreateLoginSessionForIdpInitiatedSso(KeycloakSession session, RealmModel realm, ClientModel client, String relayState) {
    String[] bindingProperties = getUrlAndBindingForIdpInitiatedSso(client);
    if (bindingProperties == null) {
        return null;
    }
    String redirect = bindingProperties[0];
    String bindingType = bindingProperties[1];
    AuthenticationSessionModel authSession = createAuthenticationSession(client, null);
    authSession.setProtocol(SamlProtocol.LOGIN_PROTOCOL);
    authSession.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name());
    authSession.setClientNote(SamlProtocol.SAML_BINDING, bindingType);
    authSession.setClientNote(SamlProtocol.SAML_IDP_INITIATED_LOGIN, "true");
    authSession.setRedirectUri(redirect);
    if (relayState == null) {
        relayState = client.getAttribute(SamlProtocol.SAML_IDP_INITIATED_SSO_RELAY_STATE);
    }
    if (relayState != null && !relayState.trim().equals("")) {
        authSession.setClientNote(GeneralConstants.RELAY_STATE, relayState);
    }
    return authSession;
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel)

Example 20 with AuthenticationSessionModel

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

the class DeclarativeUserProfileProvider method requestedScopePredicate.

/**
 * Method used for predicate which returns true if any of the configuredScopes is requested in current auth flow.
 *
 * @param context to get current auth flow from
 * @param configuredScopes to be evaluated
 * @return
 */
private static boolean requestedScopePredicate(AttributeContext context, Set<String> configuredScopes) {
    KeycloakSession session = context.getSession();
    AuthenticationSessionModel authenticationSession = session.getContext().getAuthenticationSession();
    if (authenticationSession == null) {
        return false;
    }
    String requestedScopesString = authenticationSession.getClientNote(OIDCLoginProtocol.SCOPE_PARAM);
    ClientModel client = authenticationSession.getClient();
    return getRequestedClientScopes(requestedScopesString, client).map((csm) -> csm.getName()).anyMatch(configuredScopes::contains);
}
Also used : ClientModel(org.keycloak.models.ClientModel) UPConfigUtils(org.keycloak.userprofile.config.UPConfigUtils) Profile(org.keycloak.common.Profile) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) HashMap(java.util.HashMap) Config(org.keycloak.Config) Messages(org.keycloak.services.messages.Messages) TokenManager.getRequestedClientScopes(org.keycloak.protocol.oidc.TokenManager.getRequestedClientScopes) ArrayList(java.util.ArrayList) AmphibianProviderFactory(org.keycloak.component.AmphibianProviderFactory) AbstractSimpleValidator(org.keycloak.validate.AbstractSimpleValidator) UserModel(org.keycloak.models.UserModel) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) DeclarativeUserProfileModel(org.keycloak.userprofile.config.DeclarativeUserProfileModel) UPConfigUtils.readConfig(org.keycloak.userprofile.config.UPConfigUtils.readConfig) ComponentModel(org.keycloak.component.ComponentModel) AttributeRequiredByMetadataValidator(org.keycloak.userprofile.validator.AttributeRequiredByMetadataValidator) UPGroup(org.keycloak.userprofile.config.UPGroup) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) UPAttributeSelector(org.keycloak.userprofile.config.UPAttributeSelector) ImmutableAttributeValidator(org.keycloak.userprofile.validator.ImmutableAttributeValidator) ValidatorConfig(org.keycloak.validate.ValidatorConfig) UPAttribute(org.keycloak.userprofile.config.UPAttribute) Predicate(java.util.function.Predicate) UPAttributeRequired(org.keycloak.userprofile.config.UPAttributeRequired) Set(java.util.Set) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) UPConfig(org.keycloak.userprofile.config.UPConfig) List(java.util.List) ObjectUtil.isBlank(org.keycloak.common.util.ObjectUtil.isBlank) BlankAttributeValidator(org.keycloak.userprofile.validator.BlankAttributeValidator) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) UPAttributePermissions(org.keycloak.userprofile.config.UPAttributePermissions) EmailValidator(org.keycloak.validate.validators.EmailValidator) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) Collections(java.util.Collections) ComponentValidationException(org.keycloak.component.ComponentValidationException) ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession)

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