Search in sources :

Example 6 with PostAuthenticationFailedException

use of org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException 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 7 with PostAuthenticationFailedException

use of org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method addConsent.

/**
 * Persist the consents received from the user, while user creation.
 *
 * @param receiptInput Relevant receipt input representing consent data.
 * @param tenantDomain Relevant tenant domain.
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private void addConsent(ReceiptInput receiptInput, String tenantDomain) throws PostAuthenticationFailedException {
    ConsentManager consentManager = FrameworkServiceDataHolder.getInstance().getConsentManager();
    if (receiptInput.getServices().size() == 0) {
        throw new PostAuthenticationFailedException(ErrorMessages.ERROR_WHILE_ADDING_CONSENT.getCode(), String.format(ErrorMessages.ERROR_WHILE_ADDING_CONSENT.getMessage(), tenantDomain));
    }
    // There should be one receipt
    ReceiptServiceInput receiptServiceInput = receiptInput.getServices().get(0);
    receiptServiceInput.setTenantDomain(tenantDomain);
    try {
        setIDPData(tenantDomain, receiptServiceInput);
        receiptInput.setTenantDomain(tenantDomain);
        consentManager.addConsent(receiptInput);
    } catch (ConsentManagementException e) {
        handleExceptions(String.format(ErrorMessages.ERROR_WHILE_ADDING_CONSENT.getMessage(), tenantDomain), ErrorMessages.ERROR_WHILE_ADDING_CONSENT.getCode(), e);
    }
}
Also used : ReceiptServiceInput(org.wso2.carbon.consent.mgt.core.model.ReceiptServiceInput) ConsentManagementException(org.wso2.carbon.consent.mgt.core.exception.ConsentManagementException) ConsentManager(org.wso2.carbon.consent.mgt.core.ConsentManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)

Example 8 with PostAuthenticationFailedException

use of org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method isAccountDisabled.

/**
 * Uses to check whether associated users account is disabled or not.
 *
 * @param username Username of the associated user.
 * @return Whether user is disabled or not.
 * @throws PostAuthenticationFailedException When getting claim value.
 */
private boolean isAccountDisabled(String username, String tenantDomain) throws PostAuthenticationFailedException {
    try {
        UserRealm realm = (UserRealm) FrameworkServiceDataHolder.getInstance().getRealmService().getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain));
        UserStoreManager userStoreManager = realm.getUserStoreManager();
        Map<String, String> claimValues = userStoreManager.getUserClaimValues(username, new String[] { AccountConstants.ACCOUNT_DISABLED_CLAIM }, UserCoreConstants.DEFAULT_PROFILE);
        if (claimValues != null && claimValues.size() > 0) {
            String accountDisabledClaim = claimValues.get(AccountConstants.ACCOUNT_DISABLED_CLAIM);
            return Boolean.parseBoolean(accountDisabledClaim);
        }
    } catch (UserStoreException e) {
        throw new PostAuthenticationFailedException(ErrorMessages.ERROR_WHILE_CHECKING_ACCOUNT_DISABLE_STATUS.getCode(), String.format(ErrorMessages.ERROR_WHILE_CHECKING_ACCOUNT_DISABLE_STATUS.getMessage(), username), e);
    }
    return false;
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)

Example 9 with PostAuthenticationFailedException

use of org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method redirectToAccountCreateUI.

/**
 * Call the relevant URL to add the new user.
 *
 * @param externalIdPConfig Relevant external IDP.
 * @param context           Authentication context.
 * @param localClaimValues  Local claim values.
 * @param response          HttpServlet response.
 * @param username          Relevant user name
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private void redirectToAccountCreateUI(ExternalIdPConfig externalIdPConfig, AuthenticationContext context, Map<String, String> localClaimValues, HttpServletResponse response, String username, HttpServletRequest request) throws PostAuthenticationFailedException {
    try {
        ServiceURLBuilder uriBuilder = ServiceURLBuilder.create();
        if (externalIdPConfig.isModifyUserNameAllowed()) {
            context.setProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED, true);
            uriBuilder = uriBuilder.addPath(FrameworkUtils.getUserNameProvisioningUIUrl());
            uriBuilder.addParameter(FrameworkConstants.ALLOW_CHANGE_USER_NAME, String.valueOf(true));
            if (log.isDebugEnabled()) {
                log.debug(externalIdPConfig.getName() + " allow to change the username, redirecting to " + "registration endpoint to provision the user: " + username);
            }
        } else {
            uriBuilder = uriBuilder.addPath(FrameworkUtils.getPasswordProvisioningUIUrl());
            if (log.isDebugEnabled()) {
                if (externalIdPConfig.isPasswordProvisioningEnabled()) {
                    log.debug(externalIdPConfig.getName() + " supports password provisioning, redirecting to " + "sign up endpoint to provision the user : " + username);
                }
            }
        }
        if (externalIdPConfig.isPasswordProvisioningEnabled()) {
            uriBuilder.addParameter(FrameworkConstants.PASSWORD_PROVISION_ENABLED, String.valueOf(true));
        }
        if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
            uriBuilder.addParameter(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME, context.getTenantDomain());
        }
        uriBuilder.addParameter(FrameworkConstants.SERVICE_PROVIDER, context.getSequenceConfig().getApplicationConfig().getApplicationName());
        uriBuilder.addParameter(FrameworkConstants.USERNAME, username);
        uriBuilder.addParameter(FrameworkConstants.SKIP_SIGN_UP_ENABLE_CHECK, String.valueOf(true));
        uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());
        addMissingClaims(uriBuilder, context);
        localClaimValues.forEach(uriBuilder::addParameter);
        response.sendRedirect(uriBuilder.build().getRelativePublicURL());
    } catch (IOException | URLBuilderException e) {
        handleExceptions(String.format(ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING.getMessage(), username, externalIdPConfig.getName()), ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING.getCode(), e);
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) IOException(java.io.IOException) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder)

Example 10 with PostAuthenticationFailedException

use of org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException in project carbon-identity-framework by wso2.

the class PostAuthAssociationHandler method setAssociatedLocalUserToContext.

/**
 * 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();
    UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedLocalUserName));
    String fullQualifiedAssociatedUserId = FrameworkUtils.prependUserStoreDomainToName(associatedLocalUserName + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
    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);
    }
}
Also used : ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)

Aggregations

PostAuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)17 HashMap (java.util.HashMap)7 StringUtils.defaultString (org.apache.commons.lang.StringUtils.defaultString)7 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)7 Map (java.util.Map)6 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)6 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)6 ApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator)5 FederatedApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator)5 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)5 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)4 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)4 UserRealm (org.wso2.carbon.user.core.UserRealm)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 ApplicationConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig)3 AuthenticatorConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig)3 ClaimMetadataException (org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException)3 FederatedAssociationManager (org.wso2.carbon.identity.user.profile.mgt.association.federation.FederatedAssociationManager)3 FederatedAssociationManagerException (org.wso2.carbon.identity.user.profile.mgt.association.federation.exception.FederatedAssociationManagerException)3