Search in sources :

Example 1 with PostAuthnHandlerFlowStatus

use of org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus in project carbon-identity-framework by wso2.

the class PostAuthenticationMgtService method executePostAuthnHandler.

/**
 * @param request               Incoming HttpServletRequest.
 * @param response              HttpServletResponse.
 * @param authenticationContext Authentication context.
 * @param currentHandler        Current post authentication handler.
 * @return Whether this handler needs to be continued or not. True if the same handler needs to be continued,
 * else false.
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private boolean executePostAuthnHandler(HttpServletRequest request, HttpServletResponse response, AuthenticationContext authenticationContext, PostAuthenticationHandler currentHandler) throws PostAuthenticationFailedException {
    if (currentHandler.isEnabled()) {
        if (log.isDebugEnabled()) {
            log.debug(currentHandler.getName() + " is enabled. Hence executing for context : " + authenticationContext.getContextIdentifier());
        }
        PostAuthnHandlerFlowStatus flowStatus = currentHandler.handle(request, response, authenticationContext);
        if (log.isDebugEnabled()) {
            log.debug("Post authentication handler " + currentHandler.getName() + " returned with status : " + flowStatus + " for context identifier : " + authenticationContext.getContextIdentifier());
        }
        if (isExecutionFinished(flowStatus)) {
            if (log.isDebugEnabled()) {
                log.debug("Post authentication handler " + currentHandler.getName() + " completed execution for session context : " + authenticationContext.getContextIdentifier());
            }
            authenticationContext.setExecutedPostAuthHandler(currentHandler.getName());
            authenticationContext.setProperty(FrameworkConstants.CURRENT_POST_AUTHENTICATION_HANDLER, null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Post authentication handler " + currentHandler.getName() + " is not completed yet. Hence" + " returning for context : " + authenticationContext.getContextIdentifier());
            }
            authenticationContext.setProperty(FrameworkConstants.CURRENT_POST_AUTHENTICATION_HANDLER, currentHandler.getName());
            return true;
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Post authentication handler " + currentHandler.getName() + " is disabled. Hence returning" + " without executing for context : " + authenticationContext.getContextIdentifier());
        }
    }
    return false;
}
Also used : PostAuthnHandlerFlowStatus(org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus)

Example 2 with PostAuthnHandlerFlowStatus

use of org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method handleResponseFlow.

/**
 * 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) {
            String externalIdPConfigName = stepConfig.getAuthenticatedIdP();
            ExternalIdPConfig 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().getLoggableUserId());
                }
                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 = getUsernameFederatedUser(stepConfig, sequenceConfig, externalIdPConfigName, context, localClaimValues, externalIdPConfig);
                if (context.getProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED) != null) {
                    username = request.getParameter(FrameworkConstants.USERNAME);
                    try {
                        /*
                            Checks whether the provided user is already existing in the system. If so an exception
                            will be thrown.
                            */
                        UserRealm realm = getUserRealm(context.getTenantDomain());
                        UserStoreManager userStoreManager = getUserStoreManager(context.getExternalIdP().getProvisioningUserStoreId(), realm, username);
                        String sanitizedUserName = UserCoreUtil.removeDomainFromName(MultitenantUtils.getTenantAwareUsername(username));
                        if (userStoreManager.isExistingUser(sanitizedUserName)) {
                            // Logging the error because the thrown exception is handled in the UI.
                            log.error(ErrorMessages.USER_ALREADY_EXISTS_ERROR.getCode() + " - " + ErrorMessages.USER_ALREADY_EXISTS_ERROR.getMessage());
                            handleExceptions(ErrorMessages.USER_ALREADY_EXISTS_ERROR.getMessage(), "provided.username.already.exists", null);
                        }
                    } catch (UserStoreException e) {
                        handleExceptions(ErrorMessages.ERROR_WHILE_CHECKING_USERNAME_EXISTENCE.getMessage(), "error.user.existence", e);
                    }
                }
                callDefaultProvisioningHandler(username, context, externalIdPConfig, combinedLocalClaims, stepConfig);
                handleConsents(request, stepConfig, context.getTenantDomain());
            }
        }
    }
    return SUCCESS_COMPLETED;
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) HashMap(java.util.HashMap) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) JSONObject(org.json.JSONObject) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with PostAuthnHandlerFlowStatus

use of org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method handleRequestFlow.

/**
 * 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 {
    String retryURL = ConfigurationFacade.getInstance().getAuthenticationEndpointRetryURL();
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    for (Map.Entry<Integer, StepConfig> entry : sequenceConfig.getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
        if (authenticatorConfig == null) {
            // ex: Different authentication sequences evaluated by the script
            continue;
        }
        ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
        if (authenticator instanceof FederatedApplicationAuthenticator) {
            String externalIdPConfigName = stepConfig.getAuthenticatedIdP();
            ExternalIdPConfig externalIdPConfig = getExternalIdpConfig(externalIdPConfigName, context);
            context.setExternalIdP(externalIdPConfig);
            Map<String, String> localClaimValues;
            if (stepConfig.isSubjectAttributeStep()) {
                localClaimValues = (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
            } else {
                localClaimValues = getLocalClaimValuesOfIDPInNonAttributeSelectionStep(context, stepConfig, externalIdPConfig);
            }
            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 = associatedLocalUser;
                // If associatedLocalUser is null, that means relevant association not exist already.
                if (StringUtils.isEmpty(associatedLocalUser)) {
                    if (log.isDebugEnabled()) {
                        log.debug(sequenceConfig.getAuthenticatedUser().getLoggableUserId() + " coming from " + externalIdPConfig.getIdPName() + " do not have a local account, hence redirecting" + " to the UI to sign up.");
                    }
                    if (externalIdPConfig.isPromptConsentEnabled()) {
                        username = getUsernameFederatedUser(stepConfig, sequenceConfig, externalIdPConfigName, context, localClaimValues, externalIdPConfig);
                        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 = getUsernameFederatedUser(stepConfig, sequenceConfig, externalIdPConfigName, context, localClaimValues, externalIdPConfig);
                }
                if (StringUtils.isNotBlank(associatedLocalUser)) {
                    // Check if the associated local account is locked.
                    if (isAccountLocked(username, context.getTenantDomain())) {
                        if (log.isDebugEnabled()) {
                            log.debug(String.format("The account is locked for the user: %s in the " + "tenant domain: %s ", username, context.getTenantDomain()));
                        }
                        String retryParam = "&authFailure=true&authFailureMsg=error.user.account.locked&errorCode=" + UserCoreConstants.ErrorCode.USER_IS_LOCKED;
                        handleAccountLockLoginFailure(retryURL, context, response, retryParam);
                        return PostAuthnHandlerFlowStatus.INCOMPLETE;
                    }
                    // Check if the associated local account is disabled.
                    if (isAccountDisabled(associatedLocalUser, context.getTenantDomain())) {
                        if (log.isDebugEnabled()) {
                            log.debug(String.format("The account is disabled for the user: %s in the " + "tenant domain: %s ", username, context.getTenantDomain()));
                        }
                        String retryParam = "&authFailure=true&authFailureMsg=error.user.account.disabled&errorCode=" + IdentityCoreConstants.USER_ACCOUNT_DISABLED_ERROR_CODE;
                        handleAccountLockLoginFailure(retryURL, context, response, retryParam);
                        return PostAuthnHandlerFlowStatus.INCOMPLETE;
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("User : " + sequenceConfig.getAuthenticatedUser().getLoggableUserId() + " coming from " + externalIdPConfig.getIdPName() + " do have a local account, with the username " + username);
                }
                callDefaultProvisioningHandler(username, context, externalIdPConfig, localClaimValues, stepConfig);
            }
        }
    }
    return SUCCESS_COMPLETED;
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with PostAuthnHandlerFlowStatus

use of org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus in project carbon-identity-framework by wso2.

the class PostAuthAssociationHandler method handle.

@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) {
            // 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;
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) HashMap(java.util.HashMap) Map(java.util.Map) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator)

Example 5 with PostAuthnHandlerFlowStatus

use of org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus in project carbon-identity-framework by wso2.

the class PostAuthenticatedSubjectIdentifierHandler method handle.

@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);
    try {
        if (StringUtils.isNotBlank(subjectClaimURI)) {
            if (subjectValue != null) {
                handleUserStoreAndTenantDomain(sequenceConfig, subjectValue);
            } else {
                log.warn("Subject claim could not be found. Defaulting to Name Identifier.");
                setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
            }
        } else {
            setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
        }
    } catch (UserIdNotFoundException e) {
        return UNSUCCESS_COMPLETED;
    }
    return SUCCESS_COMPLETED;
}
Also used : SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Aggregations

PostAuthnHandlerFlowStatus (org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus)10 Test (org.testng.annotations.Test)9 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)9 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)8 HashMap (java.util.HashMap)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)5 IdentityProviderProperty (org.wso2.carbon.identity.application.common.model.IdentityProviderProperty)5 UserRealm (org.wso2.carbon.user.core.UserRealm)5 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)5 Map (java.util.Map)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 AbstractFrameworkTest (org.wso2.carbon.identity.application.authentication.framework.AbstractFrameworkTest)4 RealmService (org.wso2.carbon.user.core.service.RealmService)4 StringUtils.defaultString (org.apache.commons.lang.StringUtils.defaultString)3 ApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator)3 FederatedApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator)3 AuthenticatorConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig)3 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)3