Search in sources :

Example 36 with AuthenticationSessionModel

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

the class LoginActionsService method processRequireAction.

private Response processRequireAction(final String authSessionId, final String code, String action, String clientId, String tabId) {
    event.event(EventType.CUSTOM_REQUIRED_ACTION);
    SessionCodeChecks checks = checksForCode(authSessionId, code, action, clientId, tabId, REQUIRED_ACTION);
    if (!checks.verifyRequiredAction(action)) {
        return checks.getResponse();
    }
    AuthenticationSessionModel authSession = checks.getAuthenticationSession();
    processLocaleParam(authSession);
    if (!checks.isActionRequest()) {
        initLoginEvent(authSession);
        event.event(EventType.CUSTOM_REQUIRED_ACTION);
        return AuthenticationManager.nextActionAfterAuthentication(session, authSession, clientConnection, request, session.getContext().getUri(), event);
    }
    initLoginEvent(authSession);
    event.event(EventType.CUSTOM_REQUIRED_ACTION);
    event.detail(Details.CUSTOM_REQUIRED_ACTION, action);
    RequiredActionFactory factory = (RequiredActionFactory) session.getKeycloakSessionFactory().getProviderFactory(RequiredActionProvider.class, action);
    if (factory == null) {
        ServicesLogger.LOGGER.actionProviderNull();
        event.error(Errors.INVALID_CODE);
        throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.INVALID_CODE));
    }
    RequiredActionContextResult context = new RequiredActionContextResult(authSession, realm, event, session, request, authSession.getAuthenticatedUser(), factory) {

        @Override
        public void ignore() {
            throw new RuntimeException("Cannot call ignore within processAction()");
        }
    };
    RequiredActionProvider provider = null;
    try {
        provider = AuthenticationManager.createRequiredAction(context);
    } catch (AuthenticationFlowException e) {
        if (e.getResponse() != null) {
            return e.getResponse();
        }
        throw new WebApplicationException(ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.DISPLAY_UNSUPPORTED));
    }
    Response response;
    if (isCancelAppInitiatedAction(factory.getId(), authSession, context)) {
        provider.initiatedActionCanceled(session, authSession);
        AuthenticationManager.setKcActionStatus(factory.getId(), RequiredActionContext.KcActionStatus.CANCELLED, authSession);
        context.success();
    } else {
        provider.processAction(context);
    }
    if (action != null) {
        authSession.setAuthNote(AuthenticationProcessor.LAST_PROCESSED_EXECUTION, action);
    }
    if (context.getStatus() == RequiredActionContext.Status.SUCCESS) {
        event.clone().success();
        initLoginEvent(authSession);
        event.event(EventType.LOGIN);
        authSession.removeRequiredAction(factory.getId());
        authSession.getAuthenticatedUser().removeRequiredAction(factory.getId());
        authSession.removeAuthNote(AuthenticationProcessor.CURRENT_AUTHENTICATION_EXECUTION);
        AuthenticationManager.setKcActionStatus(factory.getId(), RequiredActionContext.KcActionStatus.SUCCESS, authSession);
        response = AuthenticationManager.nextActionAfterAuthentication(session, authSession, clientConnection, request, session.getContext().getUri(), event);
    } else if (context.getStatus() == RequiredActionContext.Status.CHALLENGE) {
        response = context.getChallenge();
    } else if (context.getStatus() == RequiredActionContext.Status.FAILURE) {
        response = interruptionResponse(context, authSession, action, Error.CONSENT_DENIED);
    } else {
        throw new RuntimeException("Unreachable");
    }
    return BrowserHistoryHelper.getInstance().saveResponseAndRedirect(session, authSession, response, true, request);
}
Also used : Response(javax.ws.rs.core.Response) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) RequiredActionFactory(org.keycloak.authentication.RequiredActionFactory) WebApplicationException(javax.ws.rs.WebApplicationException) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) RequiredActionContextResult(org.keycloak.authentication.RequiredActionContextResult)

Example 37 with AuthenticationSessionModel

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

the class LoginActionsService method authenticate.

/**
 * protocol independent login page entry point
 *
 * @param code
 * @return
 */
@Path(AUTHENTICATE_PATH)
@GET
public // optional, can get from cookie instead
Response authenticate(// optional, can get from cookie instead
@QueryParam(AUTH_SESSION_ID) String authSessionId, @QueryParam(SESSION_CODE) String code, @QueryParam(Constants.EXECUTION) String execution, @QueryParam(Constants.CLIENT_ID) String clientId, @QueryParam(Constants.TAB_ID) String tabId) {
    event.event(EventType.LOGIN);
    SessionCodeChecks checks = checksForCode(authSessionId, code, execution, clientId, tabId, AUTHENTICATE_PATH);
    if (!checks.verifyActiveAndValidAction(AuthenticationSessionModel.Action.AUTHENTICATE.name(), ClientSessionCode.ActionType.LOGIN)) {
        return checks.getResponse();
    }
    AuthenticationSessionModel authSession = checks.getAuthenticationSession();
    boolean actionRequest = checks.isActionRequest();
    processLocaleParam(authSession);
    return processAuthentication(actionRequest, execution, authSession, null);
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 38 with AuthenticationSessionModel

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

the class LoginActionsService method redirectToAfterBrokerLoginEndpoint.

public static Response redirectToAfterBrokerLoginEndpoint(KeycloakSession session, RealmModel realm, UriInfo uriInfo, AuthenticationSessionModel authSession, boolean firstBrokerLogin) {
    ClientSessionCode<AuthenticationSessionModel> accessCode = new ClientSessionCode<>(session, realm, authSession);
    authSession.getParentSession().setTimestamp(Time.currentTime());
    String clientId = authSession.getClient().getClientId();
    String tabId = authSession.getTabId();
    URI redirect = firstBrokerLogin ? Urls.identityProviderAfterFirstBrokerLogin(uriInfo.getBaseUri(), realm.getName(), accessCode.getOrGenerateCode(), clientId, tabId) : Urls.identityProviderAfterPostBrokerLogin(uriInfo.getBaseUri(), realm.getName(), accessCode.getOrGenerateCode(), clientId, tabId);
    logger.debugf("Redirecting to '%s' ", redirect);
    return Response.status(302).location(redirect).build();
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ClientSessionCode(org.keycloak.services.managers.ClientSessionCode) URI(java.net.URI)

Example 39 with AuthenticationSessionModel

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

the class IdentityBrokerService method performLogin.

@GET
@NoCache
@Path("/{provider_id}/login")
public Response performLogin(@PathParam("provider_id") String providerId, @QueryParam(LoginActionsService.SESSION_CODE) String code, @QueryParam("client_id") String clientId, @QueryParam(Constants.TAB_ID) String tabId, @QueryParam(OIDCLoginProtocol.LOGIN_HINT_PARAM) String loginHint) {
    this.event.detail(Details.IDENTITY_PROVIDER, providerId);
    if (isDebugEnabled()) {
        logger.debugf("Sending authentication request to identity provider [%s].", providerId);
    }
    try {
        AuthenticationSessionModel authSession = parseSessionCode(code, clientId, tabId);
        ClientSessionCode<AuthenticationSessionModel> clientSessionCode = new ClientSessionCode<>(session, realmModel, authSession);
        clientSessionCode.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name());
        IdentityProviderModel identityProviderModel = realmModel.getIdentityProviderByAlias(providerId);
        if (identityProviderModel == null) {
            throw new IdentityBrokerException("Identity Provider [" + providerId + "] not found.");
        }
        if (identityProviderModel.isLinkOnly()) {
            throw new IdentityBrokerException("Identity Provider [" + providerId + "] is not allowed to perform a login.");
        }
        if (clientSessionCode != null && clientSessionCode.getClientSession() != null && loginHint != null) {
            clientSessionCode.getClientSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, loginHint);
        }
        IdentityProviderFactory providerFactory = getIdentityProviderFactory(session, identityProviderModel);
        IdentityProvider identityProvider = providerFactory.create(session, identityProviderModel);
        Response response = identityProvider.performLogin(createAuthenticationRequest(providerId, clientSessionCode));
        if (response != null) {
            if (isDebugEnabled()) {
                logger.debugf("Identity provider [%s] is going to send a request [%s].", identityProvider, response);
            }
            return response;
        }
    } catch (IdentityBrokerException e) {
        return redirectToErrorPage(Response.Status.BAD_GATEWAY, Messages.COULD_NOT_SEND_AUTHENTICATION_REQUEST, e, providerId);
    } catch (Exception e) {
        return redirectToErrorPage(Response.Status.INTERNAL_SERVER_ERROR, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST, e, providerId);
    }
    return redirectToErrorPage(Response.Status.INTERNAL_SERVER_ERROR, Messages.COULD_NOT_PROCEED_WITH_AUTHENTICATION_REQUEST);
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) SocialIdentityProvider(org.keycloak.broker.social.SocialIdentityProvider) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) ClientSessionCode(org.keycloak.services.managers.ClientSessionCode) IdentityProviderFactory(org.keycloak.broker.provider.IdentityProviderFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) OAuthErrorException(org.keycloak.OAuthErrorException) NotFoundException(javax.ws.rs.NotFoundException) ErrorPageException(org.keycloak.services.ErrorPageException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 40 with AuthenticationSessionModel

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

the class IdentityBrokerService method parseSessionCode.

/**
 * This method will throw JAX-RS exception in case it is not able to retrieve AuthenticationSessionModel. It never returns null
 */
private AuthenticationSessionModel parseSessionCode(String code, String clientId, String tabId) {
    if (code == null || clientId == null || tabId == null) {
        logger.debugf("Invalid request. Authorization code, clientId or tabId was null. Code=%s, clientId=%s, tabID=%s", code, clientId, tabId);
        Response staleCodeError = redirectToErrorPage(Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
        throw new WebApplicationException(staleCodeError);
    }
    SessionCodeChecks checks = new SessionCodeChecks(realmModel, session.getContext().getUri(), request, clientConnection, session, event, null, code, null, clientId, tabId, LoginActionsService.AUTHENTICATE_PATH);
    checks.initialVerify();
    if (!checks.verifyActiveAndValidAction(AuthenticationSessionModel.Action.AUTHENTICATE.name(), ClientSessionCode.ActionType.LOGIN)) {
        AuthenticationSessionModel authSession = checks.getAuthenticationSession();
        if (authSession != null) {
            // Check if error happened during login or during linking from account management
            Response accountManagementFailedLinking = checkAccountManagementFailedLinking(authSession, Messages.STALE_CODE_ACCOUNT);
            if (accountManagementFailedLinking != null) {
                throw new WebApplicationException(accountManagementFailedLinking);
            } else {
                Response errorResponse = checks.getResponse();
                // Remove "code" from browser history
                errorResponse = BrowserHistoryHelper.getInstance().saveResponseAndRedirect(session, authSession, errorResponse, true, request);
                throw new WebApplicationException(errorResponse);
            }
        } else {
            throw new WebApplicationException(checks.getResponse());
        }
    } else {
        if (isDebugEnabled()) {
            logger.debugf("Authorization code is valid.");
        }
        return checks.getClientCode().getClientSession();
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) WebApplicationException(javax.ws.rs.WebApplicationException)

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