Search in sources :

Example 1 with CustomScriptConfiguration

use of io.jans.model.custom.script.conf.CustomScriptConfiguration in project jans by JanssenProject.

the class ConsentGathererService method configure.

public boolean configure(String userDn, String clientId, String state) {
    final HttpServletRequest httpRequest = (HttpServletRequest) externalContext.getRequest();
    final HttpServletResponse httpResponse = (HttpServletResponse) externalContext.getResponse();
    final SessionId session = sessionService.getConsentSession(httpRequest, httpResponse, userDn, true);
    CustomScriptConfiguration script = determineConsentScript(clientId);
    if (script == null) {
        log.error("Failed to determine consent-gathering script");
        return false;
    }
    sessionService.configure(session, script.getName(), clientId, state);
    this.context = new ConsentGatheringContext(script.getConfigurationAttributes(), httpRequest, httpResponse, session, pageAttributes, sessionService, userService, facesService, appConfiguration);
    log.debug("Configuring consent-gathering script '{}'", script.getName());
    int step = sessionService.getStep(session);
    String redirectTo = external.getPageForStep(script, step, context);
    if (StringHelper.isEmpty(redirectTo)) {
        log.error("Failed to determine page for consent-gathering script");
        return false;
    }
    context.persist();
    log.trace("Redirecting to page: '{}'", redirectTo);
    facesService.redirectWithExternal(redirectTo, null);
    return true;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ConsentGatheringContext(io.jans.as.server.service.external.context.ConsentGatheringContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionId(io.jans.as.server.model.common.SessionId) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 2 with CustomScriptConfiguration

use of io.jans.model.custom.script.conf.CustomScriptConfiguration in project jans by JanssenProject.

the class ConsentGathererService method prepareForStep.

public String prepareForStep() {
    try {
        final HttpServletRequest httpRequest = (HttpServletRequest) externalContext.getRequest();
        final HttpServletResponse httpResponse = (HttpServletResponse) externalContext.getResponse();
        final SessionId session = sessionService.getConsentSession(httpRequest, httpResponse, null, false);
        if (session == null || session.getSessionAttributes().isEmpty()) {
            log.error("Failed to restore claim-gathering session state");
            return result(Constants.RESULT_EXPIRED);
        }
        CustomScriptConfiguration script = getScript(session);
        if (script == null) {
            log.error("Failed to find script '{}' in session:", sessionService.getScriptName(session));
            return result(Constants.RESULT_FAILURE);
        }
        int step = sessionService.getStep(session);
        if (step < 1) {
            log.error("Invalid step: {}", step);
            return result(Constants.RESULT_INVALID_STEP);
        }
        if (!sessionService.isPassedPreviousSteps(session, step)) {
            log.error("There are consent-gathering steps not marked as passed. scriptName: '{}', step: '{}'", script.getName(), step);
            return result(Constants.RESULT_FAILURE);
        }
        this.context = new ConsentGatheringContext(script.getConfigurationAttributes(), httpRequest, httpResponse, session, pageAttributes, sessionService, userService, facesService, appConfiguration);
        boolean result = external.prepareForStep(script, step, context);
        log.debug("Consent-gathering prepare for step result for script '{}', step: '{}', gatheredResult: '{}'", script.getName(), step, result);
        if (result) {
            context.persist();
            return result(Constants.RESULT_SUCCESS);
        }
    } catch (Exception ex) {
        log.error("Failed to prepareForStep()", ex);
    }
    return result(Constants.RESULT_FAILURE);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ConsentGatheringContext(io.jans.as.server.service.external.context.ConsentGatheringContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionId(io.jans.as.server.model.common.SessionId) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 3 with CustomScriptConfiguration

use of io.jans.model.custom.script.conf.CustomScriptConfiguration in project jans by JanssenProject.

the class LogoutAction method processExternalAuthenticatorLogOut.

private ExternalLogoutResult processExternalAuthenticatorLogOut(SessionId sessionId) {
    if ((sessionId != null) && sessionId.getSessionAttributes().containsKey(EXTERNAL_LOGOUT)) {
        log.debug("Detected callback from external system. Resuming logout.");
        return ExternalLogoutResult.SUCCESS;
    }
    AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
    if (authorizationGrant == null) {
        Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
        if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
            authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
        }
    }
    if ((authorizationGrant == null) && (sessionId == null)) {
        return ExternalLogoutResult.FAILURE;
    }
    String acrValues;
    if (authorizationGrant == null) {
        acrValues = sessionIdService.getAcr(sessionId);
    } else {
        acrValues = authorizationGrant.getAcrValues();
    }
    boolean isExternalAuthenticatorLogoutPresent = StringHelper.isNotEmpty(acrValues);
    if (isExternalAuthenticatorLogoutPresent) {
        log.debug("Attemptinmg to execute logout method of '{}' external authenticator.", acrValues);
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfigurationByName(acrValues);
        if (customScriptConfiguration == null) {
            log.error("Failed to get ExternalAuthenticatorConfiguration. acr_values: {}", acrValues);
            return ExternalLogoutResult.FAILURE;
        } else {
            boolean scriptExternalLogoutResult = externalAuthenticationService.executeExternalLogout(customScriptConfiguration, null);
            ExternalLogoutResult externalLogoutResult = scriptExternalLogoutResult ? ExternalLogoutResult.SUCCESS : ExternalLogoutResult.FAILURE;
            final String userDn = sessionId != null ? sessionId.getUserDn() : "";
            final String sId = sessionId != null ? sessionId.getId() : "";
            log.debug("Logout result is '{}' for session '{}', userDn: '{}'", externalLogoutResult, sId, userDn);
            int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
            if (apiVersion < 3) {
                // Not support redirect to external system at logout
                return externalLogoutResult;
            }
            log.trace("According to API version script supports logout redirects");
            String logoutExternalUrl = externalAuthenticationService.getLogoutExternalUrl(customScriptConfiguration, null);
            log.debug("External logout result is '{}' for user '{}'", logoutExternalUrl, userDn);
            if (StringHelper.isEmpty(logoutExternalUrl)) {
                return externalLogoutResult;
            }
            // Store in session parameters needed to call end_session
            try {
                storeLogoutParametersInSession(sessionId);
            } catch (IOException ex) {
                log.debug("Failed to persist logout parameters in session", ex);
                return ExternalLogoutResult.FAILURE;
            }
            // Redirect to external URL
            facesService.redirectToExternalURL(logoutExternalUrl);
            return ExternalLogoutResult.REDIRECT;
        }
    } else {
        return ExternalLogoutResult.SUCCESS;
    }
}
Also used : IOException(java.io.IOException) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 4 with CustomScriptConfiguration

use of io.jans.model.custom.script.conf.CustomScriptConfiguration in project jans by JanssenProject.

the class Authenticator method prepareAuthenticationForStep.

public String prepareAuthenticationForStep(SessionId sessionId) {
    Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
    if (sessionIdAttributes == null) {
        logger.debug("Unable to get attributes from session");
        return Constants.RESULT_EXPIRED;
    }
    // Set current state into identity to allow use in login form and
    // authentication scripts
    identity.setSessionId(sessionId);
    if (!externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE)) {
        return Constants.RESULT_SUCCESS;
    }
    initCustomAuthenticatorVariables(sessionIdAttributes);
    if (StringHelper.isEmpty(this.authAcr)) {
        return Constants.RESULT_SUCCESS;
    }
    if ((this.authStep == null) || (this.authStep < 1)) {
        return Constants.RESULT_NO_PERMISSIONS;
    }
    CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authAcr);
    if (customScriptConfiguration == null) {
        logger.error("Failed to get CustomScriptConfiguration. auth_step: '{}', acr: '{}'", this.authStep, this.authAcr);
        return Constants.RESULT_FAILURE;
    }
    // Check if all previous steps had passed
    boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep);
    if (!passedPreviousSteps) {
        logger.error("There are authentication steps not marked as passed. acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
        return Constants.RESULT_FAILURE;
    }
    // Restore identity working parameters from session
    setIdentityWorkingParameters(sessionIdAttributes);
    String currentauthAcr = customScriptConfiguration.getName();
    customScriptConfiguration = externalAuthenticationService.determineExternalAuthenticatorForWorkflow(AuthenticationScriptUsageType.INTERACTIVE, customScriptConfiguration);
    if (customScriptConfiguration == null) {
        return Constants.RESULT_FAILURE;
    }
    String determinedauthAcr = customScriptConfiguration.getName();
    if (!StringHelper.equalsIgnoreCase(currentauthAcr, determinedauthAcr)) {
        // Redirect user to alternative login workflow
        String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, this.authStep);
        if (StringHelper.isEmpty(redirectTo)) {
            redirectTo = "/login.xhtml";
        }
        CustomScriptConfiguration determinedCustomScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, determinedauthAcr);
        if (determinedCustomScriptConfiguration == null) {
            logger.error("Failed to get determined CustomScriptConfiguration. auth_step: '{}', acr: '{}'", this.authStep, this.authAcr);
            return Constants.RESULT_FAILURE;
        }
        logger.debug("Redirect to page: '{}'. Force to use acr: '{}'", redirectTo, determinedauthAcr);
        determinedauthAcr = determinedCustomScriptConfiguration.getName();
        String determinedAuthLevel = Integer.toString(determinedCustomScriptConfiguration.getLevel());
        sessionIdAttributes.put("acr", determinedauthAcr);
        sessionIdAttributes.put("auth_level", determinedAuthLevel);
        sessionIdAttributes.put(AUTH_STEP, Integer.toString(1));
        // Remove old session parameters from session
        if (isFalse(appConfiguration.getKeepAuthenticatorAttributesOnAcrChange())) {
            authenticationService.clearExternalScriptExtraParameters(sessionIdAttributes);
        }
        if (sessionId != null) {
            boolean updateResult = updateSession(sessionId, sessionIdAttributes);
            if (!updateResult) {
                return Constants.RESULT_EXPIRED;
            }
        }
        facesService.redirectWithExternal(redirectTo, null);
        return Constants.RESULT_SUCCESS;
    }
    return executeExternalPrepareForStep(sessionId, sessionIdAttributes, customScriptConfiguration);
}
Also used : CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 5 with CustomScriptConfiguration

use of io.jans.model.custom.script.conf.CustomScriptConfiguration in project jans by JanssenProject.

the class Authenticator method userAuthenticationInteractive.

private String userAuthenticationInteractive(HttpServletRequest servletRequest) {
    SessionId sessionId = getSessionId(servletRequest);
    Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
    if (sessionIdAttributes == null) {
        logger.debug("Unable to get session attributes. SessionId: {}", (sessionId != null ? sessionId.getId() : null));
        return Constants.RESULT_EXPIRED;
    }
    // Set current state into identity to allow use in login form and
    // authentication scripts
    identity.setSessionId(sessionId);
    initCustomAuthenticatorVariables(sessionIdAttributes);
    boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
    if (useExternalAuthenticator && !StringHelper.isEmpty(this.authAcr)) {
        initCustomAuthenticatorVariables(sessionIdAttributes);
        if ((this.authStep == null) || StringHelper.isEmpty(this.authAcr)) {
            logger.error("Failed to determine authentication mode");
            return Constants.RESULT_EXPIRED;
        }
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authAcr);
        if (customScriptConfiguration == null) {
            logger.error("Failed to get CustomScriptConfiguration for acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
            return Constants.RESULT_FAILURE;
        }
        // Check if all previous steps had passed
        boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep);
        if (!passedPreviousSteps) {
            logger.error("There are authentication steps not marked as passed. acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
            return Constants.RESULT_FAILURE;
        }
        // Restore identity working parameters from session
        setIdentityWorkingParameters(sessionIdAttributes);
        boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
        if (logger.isDebugEnabled()) {
            String userId = credentials.getUsername();
            if (StringHelper.isEmpty(userId)) {
                User user = identity.getUser();
                if (user != null) {
                    userId = user.getUserId();
                }
                logger.debug("Authentication result for user '{}'. auth_step: '{}', result: '{}', credentials: '{}'", userId, this.authStep, result, System.identityHashCode(credentials));
            }
        }
        int overridenNextStep = -1;
        logger.trace("################## acr: {}, step: {}", authAcr, authStep);
        int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
        if (apiVersion > 1) {
            logger.trace("According to API version script supports steps overriding");
            overridenNextStep = externalAuthenticationService.getNextStep(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
            logger.debug("Get next step from script: '{}'", overridenNextStep);
        }
        if (!result && (overridenNextStep == -1)) {
            // Force session lastUsedAt update if authentication attempt is failed
            sessionIdService.updateSessionId(sessionId);
            return Constants.RESULT_AUTHENTICATION_FAILED;
        }
        boolean overrideCurrentStep = false;
        if (overridenNextStep > -1) {
            overrideCurrentStep = true;
            // Reset to specified step
            sessionId = sessionIdService.resetToStep(sessionId, overridenNextStep);
            if (sessionId == null) {
                return Constants.RESULT_AUTHENTICATION_FAILED;
            }
            this.authStep = overridenNextStep;
            logger.info("Authentication reset to step : '{}'", this.authStep);
        }
        // Update parameters map to allow access it from count
        // authentication steps method
        updateExtraParameters(customScriptConfiguration, this.authStep + 1, sessionIdAttributes);
        // Determine count authentication methods
        int countAuthenticationSteps = externalAuthenticationService.executeExternalGetCountAuthenticationSteps(customScriptConfiguration);
        sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
        // Prepare for next step
        if ((this.authStep < countAuthenticationSteps) || overrideCurrentStep) {
            int nextStep;
            if (overrideCurrentStep) {
                nextStep = overridenNextStep;
            } else {
                nextStep = this.authStep + 1;
            }
            String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, nextStep);
            if (redirectTo == null) {
                return Constants.RESULT_FAILURE;
            } else if (StringHelper.isEmpty(redirectTo)) {
                redirectTo = "/login.xhtml";
            }
            // Store/Update extra parameters in session attributes map
            updateExtraParameters(customScriptConfiguration, nextStep, sessionIdAttributes);
            if (!overrideCurrentStep) {
                // Update auth_step
                sessionIdAttributes.put(AUTH_STEP, Integer.toString(nextStep));
                // Mark step as passed
                markAuthStepAsPassed(sessionIdAttributes, this.authStep);
            }
            if (sessionId != null) {
                boolean updateResult = updateSession(sessionId, sessionIdAttributes);
                if (!updateResult) {
                    return Constants.RESULT_EXPIRED;
                }
            }
            logger.trace("Redirect to page: '{}'", redirectTo);
            facesService.redirectWithExternal(redirectTo, null);
            return Constants.RESULT_SUCCESS;
        }
        if (this.authStep == countAuthenticationSteps) {
            // Store/Update extra parameters in session attributes map
            updateExtraParameters(customScriptConfiguration, this.authStep + 1, sessionIdAttributes);
            SessionId eventSessionId = authenticationService.configureSessionUser(sessionId, sessionIdAttributes);
            authenticationService.quietLogin(credentials.getUsername());
            // Redirect to authorization workflow
            logger.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
            authenticationService.onSuccessfulLogin(eventSessionId);
            logger.info(AUTHENTICATION_SUCCESS_FOR_USER, credentials.getUsername());
            return Constants.RESULT_SUCCESS;
        }
    } else {
        if (StringHelper.isNotEmpty(credentials.getUsername())) {
            boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword());
            if (authenticated) {
                SessionId eventSessionId = authenticationService.configureSessionUser(sessionId, sessionIdAttributes);
                // Redirect to authorization workflow
                logger.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
                authenticationService.onSuccessfulLogin(eventSessionId);
            } else {
                // Force session lastUsedAt update if authentication attempt is failed
                sessionIdService.updateSessionId(sessionId);
            }
            logger.info(AUTHENTICATION_SUCCESS_FOR_USER, credentials.getUsername());
            return Constants.RESULT_SUCCESS;
        }
    }
    return Constants.RESULT_FAILURE;
}
Also used : User(io.jans.as.common.model.common.User) SessionId(io.jans.as.server.model.common.SessionId) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Aggregations

CustomScriptConfiguration (io.jans.model.custom.script.conf.CustomScriptConfiguration)47 SessionId (io.jans.as.server.model.common.SessionId)8 ArrayList (java.util.ArrayList)7 WebApplicationException (javax.ws.rs.WebApplicationException)7 HashMap (java.util.HashMap)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 CustomScript (io.jans.model.custom.script.model.CustomScript)4 Client (io.jans.as.common.model.registration.Client)3 ConsentGatheringContext (io.jans.as.server.service.external.context.ConsentGatheringContext)3 UmaGatherContext (io.jans.as.server.uma.authorization.UmaGatherContext)3 SimpleCustomProperty (io.jans.model.SimpleCustomProperty)3 AuthenticationCustomScript (io.jans.model.custom.script.model.auth.AuthenticationCustomScript)3 ClientRegistrationType (io.jans.model.custom.script.type.client.ClientRegistrationType)3 User (io.jans.as.common.model.common.User)2 Scope (io.jans.as.persistence.model.Scope)2 AuthenticationScriptUsageType (io.jans.model.AuthenticationScriptUsageType)2 CustomScriptType (io.jans.model.custom.script.CustomScriptType)2 BaseExternalType (io.jans.model.custom.script.type.BaseExternalType)2 ScimType (io.jans.model.custom.script.type.scim.ScimType)2