Java Code Examples for org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext#getSequenceConfig()

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext#getSequenceConfig() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PostAuthenticatedSubjectIdentifierHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public PostAuthnHandlerFlowStatus handle(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) {

    if (!FrameworkUtils.isStepBasedSequenceHandlerExecuted(context)) {
        return SUCCESS_COMPLETED;
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    String subjectClaimURI = sequenceConfig.getApplicationConfig().getSubjectClaimUri();
    String subjectValue = (String) context.getProperty(FrameworkConstants.SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE);
    if (StringUtils.isNotBlank(subjectClaimURI)) {
        if (subjectValue != null) {
            handleUserStoreAndTenantDomain(sequenceConfig, subjectValue);
        } else {
            log.warn("Subject claim could not be found. Defaulting to Name Identifier.");
            setAuthenticatedSujectIdentifierBasedOnUserName(sequenceConfig);
        }
    } else {
        setAuthenticatedSujectIdentifierBasedOnUserName(sequenceConfig);

    }
    return SUCCESS_COMPLETED;
}
 
Example 2
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated This method is a temporary solution and might get changed in the future.
 * It is recommended not use this method.
 *
 * @param context AuthenticationContext.
 * @return true if the handlers need to be executed, otherwise false.
 */
@Deprecated
public static boolean isStepBasedSequenceHandlerExecuted(AuthenticationContext context) {

    boolean isNeeded = true;
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
    Object isDefaultStepBasedSequenceHandlerTriggered = context
            .getProperty(FrameworkConstants.STEP_BASED_SEQUENCE_HANDLER_TRIGGERED);
    // If authenticated user is null or if step based sequence handler is not trigged, exit the flow.
    if (authenticatedUser == null || isDefaultStepBasedSequenceHandlerTriggered == null
            || !(boolean) isDefaultStepBasedSequenceHandlerTriggered) {
        isNeeded = false;
    }
    return isNeeded;
}
 
Example 3
Source File: DefaultStepHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected void handleResponse(HttpServletRequest request, HttpServletResponse response,
                              AuthenticationContext context) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Receive a response from the external party");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    int currentStep = context.getCurrentStep();
    boolean isNoneCanHandle = true;
    StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);

    for (AuthenticatorConfig authenticatorConfig : stepConfig.getAuthenticatorList()) {
        ApplicationAuthenticator authenticator = authenticatorConfig
                .getApplicationAuthenticator();

        // Call authenticate if canHandle
        if (authenticator != null && authenticator.canHandle(request)
            && (context.getCurrentAuthenticator() == null || authenticator.getName()
                .equals(context.getCurrentAuthenticator()))) {
            isNoneCanHandle = false;

            if (log.isDebugEnabled()) {
                log.debug(authenticator.getName() + " can handle the request.");
            }

            doAuthentication(request, response, context, authenticatorConfig);
            break;
        }
    }
    if (isNoneCanHandle) {
        throw new FrameworkException("No authenticator can handle the request in step :  " + currentStep);
    }
}
 
Example 4
Source File: PostAuthAssociationHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To set the associated local user in automation context and to add the relevant claims.
 *
 * @param associatedLocalUserName Associated Local username.
 * @param context                 Authentication context.
 * @param stepConfig              Configuration related with current authentication step.
 * @throws PostAuthenticationFailedException Post Authentication failed exception.
 */
private void setAssociatedLocalUserToContext(String associatedLocalUserName, AuthenticationContext context,
        StepConfig stepConfig) throws PostAuthenticationFailedException {

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    String fullQualifiedAssociatedUserId = FrameworkUtils.prependUserStoreDomainToName(
            associatedLocalUserName + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
    UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedLocalUserName));
    sequenceConfig.setAuthenticatedUser(
            AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(fullQualifiedAssociatedUserId));
    sequenceConfig.getApplicationConfig().setMappedSubjectIDSelected(true);

    Map<String, String> mappedAttrs = handleClaimMappings(stepConfig, context);
    handleRoleMapping(context, sequenceConfig, mappedAttrs);
    Map<ClaimMapping, String> authenticatedUserAttributes = getClaimMapping(context, mappedAttrs);
    if (MapUtils.isNotEmpty(authenticatedUserAttributes)) {
        sequenceConfig.getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
        if (log.isDebugEnabled()) {
            log.debug("Local claims from the local user: " + associatedLocalUserName + ", set as "
                    + "user attributed for the federated scenario");
        }
    }
    // in this case associatedID is a local user name - belongs to a tenant in IS.
    String tenantDomain = MultitenantUtils.getTenantDomain(associatedLocalUserName);
    Map<String, Object> authProperties = context.getProperties();

    if (authProperties == null) {
        authProperties = new HashMap<>();
        context.setProperties(authProperties);
    }
    authProperties.put(USER_TENANT_DOMAIN, tenantDomain);
    if (log.isDebugEnabled()) {
        log.debug(
                "Authenticated User: " + sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
        log.debug("Authenticated User Tenant Domain: " + tenantDomain);
    }
}
 
Example 5
Source File: DefaultStepHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected void handleResponse(HttpServletRequest request, HttpServletResponse response,
                              AuthenticationContext context) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Receive a response from the external party");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    int currentStep = context.getCurrentStep();
    boolean isNoneCanHandle = true;
    StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);

    for (AuthenticatorConfig authenticatorConfig : stepConfig.getAuthenticatorList()) {
        ApplicationAuthenticator authenticator = authenticatorConfig
                .getApplicationAuthenticator();

        // Call authenticate if canHandle
        if (authenticator != null && authenticator.canHandle(request)
            && (context.getCurrentAuthenticator() == null || authenticator.getName()
                .equals(context.getCurrentAuthenticator()))) {
            isNoneCanHandle = false;

            if (log.isDebugEnabled()) {
                log.debug(authenticator.getName() + " can handle the request.");
            }

            doAuthentication(request, response, context, authenticatorConfig);
            break;
        }
    }
    if (isNoneCanHandle) {
        throw new FrameworkException("No authenticator can handle the request in step :  " + currentStep);
    }
}
 
Example 6
Source File: AbstractApplicationAuthenticator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected boolean retryAuthenticationEnabled(AuthenticationContext context) {
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    AuthenticationGraph graph = sequenceConfig.getAuthenticationGraph();
    if (graph == null || !graph.isEnabled()) {
        return retryAuthenticationEnabled();
    }
    return false;
}
 
Example 7
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Specially handle role claim values.
 *
 * @param context Authentication context.
 * @param mappedAttrs Mapped claim attributes.
 */
private void handleRoleClaim(AuthenticationContext context, Map<String, String> mappedAttrs) {

    if (mappedAttrs.containsKey(FrameworkConstants.LOCAL_ROLE_CLAIM_URI)) {
        String[] groups = mappedAttrs.get(FrameworkConstants.LOCAL_ROLE_CLAIM_URI).split(Pattern
                .quote(FrameworkUtils.getMultiAttributeSeparator()));
        SequenceConfig sequenceConfig = context.getSequenceConfig();
        // Execute only if it has allowed removing userstore domain from the sp level configurations.
        if (isRemoveUserDomainInRole(sequenceConfig)) {
            mappedAttrs.put(FrameworkConstants.LOCAL_ROLE_CLAIM_URI, FrameworkUtils
                    .removeDomainFromNamesExcludeHybrid(Arrays.asList(groups)));
        }
    }
}
 
Example 8
Source File: DefaultRequestPathBasedSequenceHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
protected void handlePostAuthentication(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationContext context,
                                        AuthenticatedIdPData authenticatedIdPData) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Handling Post Authentication tasks");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    Map<String, String> mappedAttrs;
    StringBuilder jsonBuilder = new StringBuilder();

    // build the authenticated idps JWT to send to the calling servlet.
    jsonBuilder.append("\"idps\":");
    jsonBuilder.append("[");

    // build the JSON object for this step
    jsonBuilder.append("{");
    jsonBuilder.append("\"idp\":\"").append(authenticatedIdPData.getIdpName()).append("\",");
    jsonBuilder
            .append("\"authenticator\":\"")
            .append(authenticatedIdPData.getAuthenticator().getApplicationAuthenticator()
                            .getName()).append("\"");
    // wrap up the JSON object
    jsonBuilder.append("}");
    jsonBuilder.append("]");

    sequenceConfig.setAuthenticatedIdPs(IdentityApplicationManagementUtil.getSignedJWT(jsonBuilder.toString(),
                    sequenceConfig.getApplicationConfig().getServiceProvider()));

    mappedAttrs = handleClaimMappings(context);
    String spRoleUri = getSpRoleClaimUri(sequenceConfig.getApplicationConfig());
    String roleAttr = mappedAttrs.get(spRoleUri);

    if (StringUtils.isNotBlank(roleAttr)) {
        String[] roles = roleAttr.split(Pattern.quote(FrameworkUtils.getMultiAttributeSeparator()));
        mappedAttrs.put(spRoleUri, getServiceProviderMappedUserRoles(sequenceConfig, Arrays.asList(roles)));
    }

    sequenceConfig.getAuthenticatedUser().setUserAttributes(FrameworkUtils.buildClaimMappings(mappedAttrs));

    if (StringUtils.isNotBlank(context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri())) {
        Map<String, String> unfilteredClaimValues =
                (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);

        String subjectClaimUri = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri().trim();
        String subjectClaimValue;
        if (unfilteredClaimValues != null) {
            subjectClaimValue = unfilteredClaimValues.get(subjectClaimUri);
        } else {
            subjectClaimValue = mappedAttrs.get(subjectClaimUri);
        }
        if (subjectClaimValue != null) {
            AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
            authenticatedUser.setAuthenticatedSubjectIdentifier(subjectClaimValue);

            if (log.isDebugEnabled()) {
                log.debug("Authenticated User: " +
                          sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
                log.debug("Authenticated User Tenant Domain: " + sequenceConfig.getAuthenticatedUser().getTenantDomain());
            }
        }
    }
}
 
Example 9
Source File: DefaultRequestPathBasedSequenceHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void handlePostAuthentication(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationContext context,
                                        AuthenticatedIdPData authenticatedIdPData) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Handling Post Authentication tasks");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    Map<String, String> mappedAttrs;
    StringBuilder jsonBuilder = new StringBuilder();

    // build the authenticated idps JWT to send to the calling servlet.
    jsonBuilder.append("\"idps\":");
    jsonBuilder.append("[");

    // build the JSON object for this step
    jsonBuilder.append("{");
    jsonBuilder.append("\"idp\":\"").append(authenticatedIdPData.getIdpName()).append("\",");
    jsonBuilder
            .append("\"authenticator\":\"")
            .append(authenticatedIdPData.getAuthenticator().getApplicationAuthenticator()
                            .getName()).append("\"");
    // wrap up the JSON object
    jsonBuilder.append("}");
    jsonBuilder.append("]");

    sequenceConfig
            .setAuthenticatedIdPs(IdentityApplicationManagementUtil.getSignedJWT(jsonBuilder
                                                                                         .toString(), sequenceConfig.getApplicationConfig().getServiceProvider()));

    mappedAttrs = handleClaimMappings(context);
    String spRoleUri = getSpRoleClaimUri(sequenceConfig.getApplicationConfig());
    String roleAttr = mappedAttrs.get(spRoleUri);

    if (roleAttr != null && roleAttr.trim().length() > 0) {

        String[] roles = roleAttr.split(",");
        mappedAttrs.put(spRoleUri,
                        getServiceProviderMappedUserRoles(sequenceConfig, Arrays.asList(roles)));
    }

    sequenceConfig.getAuthenticatedUser().setUserAttributes(FrameworkUtils.buildClaimMappings(mappedAttrs));

    if (context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri() != null
        && context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri().trim()
                   .length() > 0) {
        Map<String, String> unfilteredClaimValues = (Map<String, String>) context
                .getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);

        String subjectValue = null;

        if (unfilteredClaimValues != null) {
            subjectValue = unfilteredClaimValues.get(context.getSequenceConfig()
                                                             .getApplicationConfig().getSubjectClaimUri().trim());
        } else {
            subjectValue = mappedAttrs.get(context.getSequenceConfig().getApplicationConfig()
                                                   .getSubjectClaimUri().trim());
        }
        if (subjectValue != null) {
            AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
            authenticatedUser.setAuthenticatedSubjectIdentifier(subjectValue);

            if (log.isDebugEnabled()) {
                log.debug("Authenticated User: " +
                          sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
                log.debug("Authenticated User Tenant Domain: " + sequenceConfig.getAuthenticatedUser().getTenantDomain());
            }
        }
    }
}
 
Example 10
Source File: DefaultStepHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void handleRequestFromLoginPage(HttpServletRequest request,
                                          HttpServletResponse response, AuthenticationContext context)
        throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Relieved a request from the multi option page");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    int currentStep = context.getCurrentStep();
    StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);

    // if request from the login page with a selected IdP
    String selectedIdp = request.getParameter(FrameworkConstants.RequestParams.IDP);

    if (selectedIdp != null) {

        if (log.isDebugEnabled()) {
            log.debug("User has selected IdP: " + selectedIdp);
        }

        try {
            ExternalIdPConfig externalIdPConfig = ConfigurationFacade.getInstance()
                .getIdPConfigByName(selectedIdp, context.getTenantDomain());
            // TODO [IMPORTANT] validate the idp is inside the step.
            context.setExternalIdP(externalIdPConfig);
        } catch (IdentityProviderManagementException e) {
            log.error("Exception while getting IdP by name", e);
        }
    }

    for (AuthenticatorConfig authenticatorConfig : stepConfig.getAuthenticatorList()) {
        ApplicationAuthenticator authenticator = authenticatorConfig
                .getApplicationAuthenticator();
        // TODO [IMPORTANT] validate the authenticator is inside the step.
        if (authenticator != null && authenticator.getName().equalsIgnoreCase(
                request.getParameter(FrameworkConstants.RequestParams.AUTHENTICATOR))) {
            doAuthentication(request, response, context, authenticatorConfig);
            return;
        }
    }

    // TODO handle idp null

    // TODO handle authenticator name unmatching
}
 
Example 11
Source File: DefaultLogoutRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void sendResponse(HttpServletRequest request, HttpServletResponse response,
                            AuthenticationContext context, boolean isLoggedOut)
        throws ServletException, IOException {

    if (log.isTraceEnabled()) {
        log.trace("Inside sendLogoutResponseToCaller()");
    }

    // Set values to be returned to the calling servlet as request
    // attributes
    request.setAttribute(FrameworkConstants.ResponseParams.LOGGED_OUT, isLoggedOut);

    String redirectURL;

    if(context.getCallerSessionKey() != null) {
        request.setAttribute(FrameworkConstants.SESSION_DATA_KEY, context.getCallerSessionKey());

        AuthenticationResult authenticationResult = new AuthenticationResult();
        authenticationResult.setLoggedOut(true);

        SequenceConfig sequenceConfig = context.getSequenceConfig();
        if (sequenceConfig != null) {
            authenticationResult.setSaaSApp(sequenceConfig.getApplicationConfig().isSaaSApp());
        }

        if (FrameworkUtils.getCacheDisabledAuthenticators().contains(context.getRequestType())
                && (response instanceof CommonAuthResponseWrapper)) {
            //Set authentication result as request attribute
            addAuthenticationResultToRequest(request, authenticationResult);
        }else{
            FrameworkUtils.addAuthenticationResultToCache(context.getCallerSessionKey(), authenticationResult);
        }

        redirectURL = context.getCallerPath() + "?sessionDataKey=" + context.getCallerSessionKey();
    } else {
        redirectURL = context.getCallerPath();
    }
    
    /*
     * TODO Cache retaining is a temporary fix. Remove after Google fixes
     * http://code.google.com/p/gdata-issues/issues/detail?id=6628
     */
    String retainCache = System.getProperty("retainCache");

    if (retainCache == null) {
        FrameworkUtils.removeAuthenticationContextFromCache(context.getContextIdentifier());
    }

    if (log.isDebugEnabled()) {
        log.debug("Sending response back to: " + context.getCallerPath() + "...\n"
                  + FrameworkConstants.ResponseParams.LOGGED_OUT + " : " + isLoggedOut + "\n"
                  + FrameworkConstants.SESSION_DATA_KEY + ": " + context.getCallerSessionKey());
    }

    // redirect to the caller
    response.sendRedirect(redirectURL);
}
 
Example 12
Source File: DefaultAuthenticationRequestHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the authentication flow
 *
 * @param request
 * @param response
 * @throws FrameworkException
 */
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
                   AuthenticationContext context) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("In authentication flow");
    }

    if (context.isReturning()) {
        // if "Deny" or "Cancel" pressed on the login page.
        if (request.getParameter(FrameworkConstants.RequestParams.DENY) != null) {
            handleDenyFromLoginPage(request, response, context);
            return;
        }

        // handle remember-me option from the login page
        handleRememberMeOptionFromLoginPage(request, context);
    }

    int currentStep = context.getCurrentStep();

    // if this is the start of the authentication flow
    if (currentStep == 0) {
        handleSequenceStart(request, response, context);
    }

    SequenceConfig seqConfig = context.getSequenceConfig();
    List<AuthenticatorConfig> reqPathAuthenticators = seqConfig.getReqPathAuthenticators();

    // if SP has request path authenticators configured and this is start of
    // the flow
    if (reqPathAuthenticators != null && !reqPathAuthenticators.isEmpty() && currentStep == 0) {
        // call request path sequence handler
        FrameworkUtils.getRequestPathBasedSequenceHandler().handle(request, response, context);
    }

    // if no request path authenticators or handler returned cannot handle
    if (!context.getSequenceConfig().isCompleted()
        || (reqPathAuthenticators == null || reqPathAuthenticators.isEmpty())) {
        // call step based sequence handler
        FrameworkUtils.getStepBasedSequenceHandler().handle(request, response, context);
    }

    // if flow completed, send response back
    if (context.getSequenceConfig().isCompleted()) {
        concludeFlow(request, response, context);
    } else { // redirecting outside
        FrameworkUtils.addAuthenticationContextToCache(context.getContextIdentifier(), context);
    }
}
 
Example 13
Source File: GraphBasedSequenceHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context)
        throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Executing the Step Based Authentication...");
    }

    if (isBackToPreviousStep(context)) {
        modifyCurrentNodeAsPreviousStep(context);
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    String authenticationType = sequenceConfig.getApplicationConfig().getServiceProvider()
        .getLocalAndOutBoundAuthenticationConfig().getAuthenticationType();
    AuthenticationGraph graph = sequenceConfig.getAuthenticationGraph();
    if (graph == null || !graph.isEnabled() || (!ApplicationConstants.AUTH_TYPE_FLOW.equals(authenticationType) &&
            !ApplicationConstants.AUTH_TYPE_DEFAULT.equals(authenticationType))) {
        //Handle pre-configured step array
        if (log.isDebugEnabled()) {
            log.debug("Authentication Graph not defined for the application. "
                    + "Performing Step based authentication. Service Provider :" + sequenceConfig
                    .getApplicationId());
        }
        DefaultStepBasedSequenceHandler.getInstance().handle(request, response, context);
        return;
    }
    if (!graph.isBuildSuccessful()) {
        throw new FrameworkException(
                "Error while building graph from Javascript. Nested exception is: " + graph.getErrorReason());
    }

    boolean isInterrupted = false;
    while (!isInterrupted && !context.getSequenceConfig().isCompleted()) {

        AuthGraphNode currentNode = (AuthGraphNode) context
                .getProperty(FrameworkConstants.JSAttributes.PROP_CURRENT_NODE);
        if (currentNode == null) {
            isInterrupted = handleInitialize(request, response, context, sequenceConfig, graph);
        } else {
            isInterrupted = handleNode(request, response, context, sequenceConfig, currentNode);
        }
    }
}
 
Example 14
Source File: JITProvisioningPostAuthenticationHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * This method is used to handle response flow, after going through password provisioning.
 *
 * @param request        HttpServlet request.
 * @param context        Authentication context
 * @return Status of PostAuthnHandler flow.
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception
 */
@SuppressWarnings("unchecked")
private PostAuthnHandlerFlowStatus handleResponseFlow(HttpServletRequest request, AuthenticationContext context)
        throws PostAuthenticationFailedException {

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
        ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();

        if (authenticator instanceof FederatedApplicationAuthenticator) {
            ExternalIdPConfig externalIdPConfig;
            String externalIdPConfigName = stepConfig.getAuthenticatedIdP();
            externalIdPConfig = getExternalIdpConfig(externalIdPConfigName, context);
            context.setExternalIdP(externalIdPConfig);

            if (externalIdPConfig != null && externalIdPConfig.isProvisioningEnabled()) {
                if (log.isDebugEnabled()) {
                    log.debug("JIT provisioning response flow has hit for the IDP " + externalIdPConfigName + " "
                            + "for the user, " + sequenceConfig.getAuthenticatedUser().getUserName());
                }
                final Map<String, String> localClaimValues;
                Object unfilteredLocalClaimValues = context
                        .getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
                localClaimValues = unfilteredLocalClaimValues == null ?
                        new HashMap<>() :
                        (Map<String, String>) unfilteredLocalClaimValues;
                Map<String, String> combinedLocalClaims = getCombinedClaims(request, localClaimValues, context);
                if (externalIdPConfig.isPasswordProvisioningEnabled()) {
                    combinedLocalClaims
                            .put(FrameworkConstants.PASSWORD, request.getParameter(FrameworkConstants.PASSWORD));
                }
                String username = sequenceConfig.getAuthenticatedUser().getUserName();
                if (context.getProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED) != null) {
                    username = request.getParameter(FrameworkConstants.USERNAME);
                }
                callDefaultProvisioningHandler(username, context, externalIdPConfig, combinedLocalClaims,
                        stepConfig);
               handleConsents(request, stepConfig, context.getTenantDomain());
            }
        }
    }
    return SUCCESS_COMPLETED;
}
 
Example 15
Source File: DefaultStepHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
protected void handleRequestFromLoginPage(HttpServletRequest request,
                                          HttpServletResponse response, AuthenticationContext context)
        throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Relieved a request from the multi option page");
    }

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    int currentStep = context.getCurrentStep();
    StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);

    // if request from the login page with a selected IdP
    String selectedIdp = request.getParameter(FrameworkConstants.RequestParams.IDP);

    if (selectedIdp != null) {

        if (log.isDebugEnabled()) {
            log.debug("User has selected IdP: " + selectedIdp);
        }

        try {
            ExternalIdPConfig externalIdPConfig = ConfigurationFacade.getInstance()
                .getIdPConfigByName(selectedIdp, context.getTenantDomain());
            // TODO [IMPORTANT] validate the idp is inside the step.
            context.setExternalIdP(externalIdPConfig);
        } catch (IdentityProviderManagementException e) {
            log.error("Exception while getting IdP by name", e);
        }
    }

    for (AuthenticatorConfig authenticatorConfig : stepConfig.getAuthenticatorList()) {
        ApplicationAuthenticator authenticator = authenticatorConfig
                .getApplicationAuthenticator();
        if (authenticator != null && authenticator.getName().equalsIgnoreCase(
                request.getParameter(FrameworkConstants.RequestParams.AUTHENTICATOR))) {
            if (selectedIdp != null && authenticatorConfig.getIdps().get(selectedIdp) == null) {
                // if the selected idp name is not configured for the application, throw error since
                // this is an invalid case.
                throw new FrameworkException("Authenticators configured for application and user selected idp " +
                        "does not match. Possible tampering of parameters in login page.");
            }
            doAuthentication(request, response, context, authenticatorConfig);
            return;
        }
    }
}
 
Example 16
Source File: DefaultLogoutRequestHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
protected void sendResponse(HttpServletRequest request, HttpServletResponse response,
                            AuthenticationContext context, boolean isLoggedOut)
        throws ServletException, IOException {

    if (log.isTraceEnabled()) {
        log.trace("Inside sendLogoutResponseToCaller()");
    }

    // Set values to be returned to the calling servlet as request
    // attributes
    request.setAttribute(FrameworkConstants.ResponseParams.LOGGED_OUT, isLoggedOut);

    String redirectURL;

    if(context.getCallerSessionKey() != null) {
        request.setAttribute(FrameworkConstants.SESSION_DATA_KEY, context.getCallerSessionKey());

        AuthenticationResult authenticationResult = new AuthenticationResult();
        authenticationResult.setLoggedOut(true);

        SequenceConfig sequenceConfig = context.getSequenceConfig();
        if (sequenceConfig != null) {
            authenticationResult.setSaaSApp(sequenceConfig.getApplicationConfig().isSaaSApp());
        }

        if (FrameworkUtils.getCacheDisabledAuthenticators().contains(context.getRequestType())
                && (response instanceof CommonAuthResponseWrapper) &&
                !((CommonAuthResponseWrapper) response).isWrappedByFramework()) {
            //Set authentication result as request attribute
            addAuthenticationResultToRequest(request, authenticationResult);
        } else {
            FrameworkUtils.addAuthenticationResultToCache(context.getCallerSessionKey(), authenticationResult);
        }

        String sessionDataKeyParam = FrameworkConstants.SESSION_DATA_KEY + "=" +
                URLEncoder.encode(context.getCallerSessionKey(), "UTF-8");
        redirectURL = FrameworkUtils.appendQueryParamsStringToUrl(context.getCallerPath(), sessionDataKeyParam);
    } else {
        redirectURL = context.getCallerPath();
    }

    /*
     * TODO Cache retaining is a temporary fix. Remove after Google fixes
     * http://code.google.com/p/gdata-issues/issues/detail?id=6628
     */
    String retainCache = System.getProperty("retainCache");

    if (retainCache == null) {
        FrameworkUtils.removeAuthenticationContextFromCache(context.getContextIdentifier());
    }

    if (log.isDebugEnabled()) {
        log.debug("Sending response back to: " + context.getCallerPath() + "...\n"
                  + FrameworkConstants.ResponseParams.LOGGED_OUT + " : " + isLoggedOut + "\n"
                  + FrameworkConstants.SESSION_DATA_KEY + ": " + context.getCallerSessionKey());
    }

    // redirect to the caller
    response.sendRedirect(redirectURL);
}
 
Example 17
Source File: DefaultAuthenticationRequestHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the authentication flow
 *
 * @param request
 * @param response
 * @throws FrameworkException
 */
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
                   AuthenticationContext context) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("In authentication flow");
    }

    if (context.isReturning()) {
        // if "Deny" or "Cancel" pressed on the login page.
        if (request.getParameter(FrameworkConstants.RequestParams.DENY) != null) {
            handleDenyFromLoginPage(request, response, context);
            return;
        }

        // handle remember-me option from the login page
        handleRememberMeOptionFromLoginPage(request, context);
    }

    int currentStep = context.getCurrentStep();

    // if this is the start of the authentication flow
    if (currentStep == 0) {
        handleSequenceStart(request, response, context);
    }

    SequenceConfig seqConfig = context.getSequenceConfig();
    List<AuthenticatorConfig> reqPathAuthenticators = seqConfig.getReqPathAuthenticators();

    try {
        UserStorePreferenceOrderSupplier<List<String>> userStorePreferenceOrderSupplier =
                FrameworkUtils.getUserStorePreferenceOrderSupplier(context, null);
        if (userStorePreferenceOrderSupplier != null) {
            // Add the user store preference supplier to the container UserMgtContext.
            UserMgtContext userMgtContext = new UserMgtContext();
            userMgtContext.setUserStorePreferenceOrderSupplier(userStorePreferenceOrderSupplier);
            UserCoreUtil.setUserMgtContextInThreadLocal(userMgtContext);
        }

        // if SP has request path authenticators configured and this is start of
        // the flow
        if (reqPathAuthenticators != null && !reqPathAuthenticators.isEmpty() && currentStep == 0) {
            // call request path sequence handler
            FrameworkUtils.getRequestPathBasedSequenceHandler().handle(request, response, context);
        }

        // if no request path authenticators or handler returned cannot handle
        if (!context.getSequenceConfig().isCompleted()
                || (reqPathAuthenticators == null || reqPathAuthenticators.isEmpty())) {
            // To keep track of whether particular request goes through the step based sequence handler.
            context.setProperty(FrameworkConstants.STEP_BASED_SEQUENCE_HANDLER_TRIGGERED, true);

            // call step based sequence handler
            FrameworkUtils.getStepBasedSequenceHandler().handle(request, response, context);
        }
    } finally {
        UserCoreUtil.removeUserMgtContextInThreadLocal();
    }

    // handle post authentication
    handlePostAuthentication(request, response, context);
    // if flow completed, send response back
    if (canConcludeFlow(context)) {
        concludeFlow(request, response, context);
    }
}
 
Example 18
Source File: PostAuthAssociationHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public PostAuthnHandlerFlowStatus handle(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws PostAuthenticationFailedException {

    if (!FrameworkUtils.isStepBasedSequenceHandlerExecuted(context)) {
        return SUCCESS_COMPLETED;
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
        if (authenticatorConfig == null) {
            //May have skipped from the script
            //ex: Different authentication sequences evaluated by the script
            continue;
        }
        ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();

        if (authenticator instanceof FederatedApplicationAuthenticator) {
            if (stepConfig.isSubjectIdentifierStep()) {
                if (log.isDebugEnabled()) {
                    log.debug(authenticator.getName() + " has been set up for subject identifier step.");
                }
                 /*
                If AlwaysSendMappedLocalSubjectId is selected, need to get the local user associated with the
                federated idp.
                 */
                String associatedLocalUserName = null;
                if (sequenceConfig.getApplicationConfig().isAlwaysSendMappedLocalSubjectId()) {
                    associatedLocalUserName = getUserNameAssociatedWith(context, stepConfig);
                }
                if (StringUtils.isNotEmpty(associatedLocalUserName)) {
                    if (log.isDebugEnabled()) {
                        log.debug("AlwaysSendMappedLocalSubjectID is selected in service provider level, "
                                + "equavlent local user : " + associatedLocalUserName);
                    }
                    setAssociatedLocalUserToContext(associatedLocalUserName, context, stepConfig);
                }
            }
        }
    }
    return SUCCESS_COMPLETED;
}
 
Example 19
Source File: JITProvisioningPostAuthenticationHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * To handle the request flow of the post authentication handler.
 *
 * @param response       HttpServlet response.
 * @param context        Authentication context
 * @return Status of this post authentication handler flow.
 * @throws PostAuthenticationFailedException Exception that will be thrown in case of failure.
 */
@SuppressWarnings("unchecked")
private PostAuthnHandlerFlowStatus handleRequestFlow(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws PostAuthenticationFailedException {

    SequenceConfig sequenceConfig = context.getSequenceConfig();
    boolean isUserCreated = false;
    for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
        if (authenticatorConfig == null) {
            //May have skipped from the script
            //ex: Different authentication sequences evaluated by the script
            continue;
        }
        ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();

        if (authenticator instanceof FederatedApplicationAuthenticator) {
            ExternalIdPConfig externalIdPConfig;
            String externalIdPConfigName = stepConfig.getAuthenticatedIdP();
            externalIdPConfig = getExternalIdpConfig(externalIdPConfigName, context);
            context.setExternalIdP(externalIdPConfig);
            Map<String, String> localClaimValues = (Map<String, String>) context
                    .getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
            if (localClaimValues == null || localClaimValues.size() == 0) {
                Map<ClaimMapping, String> userAttributes = stepConfig.getAuthenticatedUser().getUserAttributes();
                localClaimValues = FrameworkUtils.getClaimMappings
                        (userAttributes, false);
            }

            if (externalIdPConfig != null && externalIdPConfig.isProvisioningEnabled()) {
                if (localClaimValues == null) {
                    localClaimValues = new HashMap<>();
                }

                String associatedLocalUser =
                        getLocalUserAssociatedForFederatedIdentifier(stepConfig.getAuthenticatedIdP(),
                                stepConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier(), context.getTenantDomain());

                String username;
                String userIdClaimUriInLocalDialect = getUserIdClaimUriInLocalDialect(externalIdPConfig);
                if (isUserNameFoundFromUserIDClaimURI(localClaimValues, userIdClaimUriInLocalDialect)) {
                    username = localClaimValues.get(userIdClaimUriInLocalDialect);
                } else {
                    username = associatedLocalUser;
                }

                // If associatedLocalUser is null, that means relevant association not exist already.
                if (StringUtils.isEmpty(associatedLocalUser) && !isUserCreated) {
                    if (log.isDebugEnabled()) {
                        log.debug(sequenceConfig.getAuthenticatedUser().getUserName() + " coming from "
                                + externalIdPConfig.getIdPName() + " do not have a local account, hence redirecting"
                                + " to the UI to sign up.");
                    }

                    if (externalIdPConfig.isPromptConsentEnabled()) {
                        if (StringUtils.isEmpty(username)) {
                            // If there is no subject claim URI configured in the IDP, get the authenticated
                            // username.
                            username = getTenantDomainAppendedUserName(
                                    sequenceConfig.getAuthenticatedUser().getUserName(), context.getTenantDomain());
                        }
                        redirectToAccountCreateUI(externalIdPConfig, context, localClaimValues, response,
                                username, request);
                        // Set the property to make sure the request is a returning one.
                        context.setProperty(FrameworkConstants.PASSWORD_PROVISION_REDIRECTION_TRIGGERED, true);
                        return PostAuthnHandlerFlowStatus.INCOMPLETE;
                    }
                }
                if (StringUtils.isEmpty(username)) {
                    username = sequenceConfig.getAuthenticatedUser().getUserName();
                    isUserCreated = true;
                }
                if (log.isDebugEnabled()) {
                    log.debug("User : " + sequenceConfig.getAuthenticatedUser().getUserName() + " coming from "
                            + externalIdPConfig.getIdPName() + " do have a local account, with the username "
                            + username);
                }
                callDefaultProvisioningHandler(username, context, externalIdPConfig, localClaimValues,
                        stepConfig);
            }
        }
    }
    return SUCCESS_COMPLETED;
}