Search in sources :

Example 1 with PostAuthenticationFailedException

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

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

the class PostAuthenticationMgtService method validatePASTRCookie.

private void validatePASTRCookie(AuthenticationContext context, HttpServletRequest request) throws PostAuthenticationFailedException {
    Object pstrCookieObj = context.getParameter(FrameworkConstants.PASTR_COOKIE);
    if (pstrCookieObj != null) {
        String storedPastrCookieValue = (String) pstrCookieObj;
        Cookie pastrCookie = FrameworkUtils.getCookie(request, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()));
        if (pastrCookie != null && StringUtils.equals(storedPastrCookieValue, pastrCookie.getValue())) {
            if (log.isDebugEnabled()) {
                log.debug("pastr cookie validated successfully for sequence : " + context.getContextIdentifier());
            }
            return;
        } else {
            throw new PostAuthenticationFailedException("Invalid Request: Your authentication flow is ended or " + "invalid. Please initiate again.", "Post authentication sequence tracking" + " cookie not found in request with context id : " + context.getContextIdentifier());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No stored pastr cookie found in authentication context for : " + context.getContextIdentifier() + " . Hence returning without validating");
        }
    }
}
Also used : Cookie(javax.servlet.http.Cookie) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)

Example 3 with PostAuthenticationFailedException

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

the class JITProvisioningPostAuthenticationHandler method getLocalClaimValuesOfIDPInNonAttributeSelectionStep.

/**
 * Uses to get local claim values of an authenticated user from an IDP in non attribute selection steps.
 *
 * @param context           Authentication Context.
 * @param stepConfig        Current step configuration.
 * @param externalIdPConfig Identity providers config.
 * @return Mapped federated user values to local claims.
 * @throws PostAuthenticationFailedException Post Authentication failed exception.
 */
private Map<String, String> getLocalClaimValuesOfIDPInNonAttributeSelectionStep(AuthenticationContext context, StepConfig stepConfig, ExternalIdPConfig externalIdPConfig) throws PostAuthenticationFailedException {
    boolean useDefaultIdpDialect = externalIdPConfig.useDefaultLocalIdpDialect();
    ApplicationAuthenticator authenticator = stepConfig.getAuthenticatedAutenticator().getApplicationAuthenticator();
    String idPStandardDialect = authenticator.getClaimDialectURI();
    Map<ClaimMapping, String> extAttrs = stepConfig.getAuthenticatedUser().getUserAttributes();
    Map<String, String> originalExternalAttributeValueMap = FrameworkUtils.getClaimMappings(extAttrs, false);
    Map<String, String> claimMapping = new HashMap<>();
    Map<String, String> localClaimValues = new HashMap<>();
    if (useDefaultIdpDialect && StringUtils.isNotBlank(idPStandardDialect)) {
        try {
            claimMapping = ClaimMetadataHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(idPStandardDialect, originalExternalAttributeValueMap.keySet(), context.getTenantDomain(), true);
        } catch (ClaimMetadataException e) {
            throw new PostAuthenticationFailedException(ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getCode(), ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getMessage(), e);
        }
    } else {
        ClaimMapping[] customClaimMapping = context.getExternalIdP().getClaimMappings();
        for (ClaimMapping externalClaim : customClaimMapping) {
            if (originalExternalAttributeValueMap.containsKey(externalClaim.getRemoteClaim().getClaimUri())) {
                claimMapping.put(externalClaim.getLocalClaim().getClaimUri(), externalClaim.getRemoteClaim().getClaimUri());
            }
        }
    }
    if (claimMapping != null && claimMapping.size() > 0) {
        for (Map.Entry<String, String> entry : claimMapping.entrySet()) {
            if (originalExternalAttributeValueMap.containsKey(entry.getValue()) && originalExternalAttributeValueMap.get(entry.getValue()) != null) {
                localClaimValues.put(entry.getKey(), originalExternalAttributeValueMap.get(entry.getValue()));
            }
        }
    }
    return localClaimValues;
}
Also used : ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) HashMap(java.util.HashMap) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with PostAuthenticationFailedException

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

the class JITProvisioningPostAuthenticationHandler method setIDPData.

/**
 * Set the IDP releated data in the receipt service input.
 *
 * @param tenantDomain        Tenant domain.
 * @param receiptServiceInput Relevant receipt service input which the
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private void setIDPData(String tenantDomain, ReceiptServiceInput receiptServiceInput) throws PostAuthenticationFailedException {
    String resideIdpDescription = "Resident IDP";
    IdentityProviderManager idpManager = IdentityProviderManager.getInstance();
    IdentityProvider residentIdP = null;
    try {
        residentIdP = idpManager.getResidentIdP(tenantDomain);
    } catch (IdentityProviderManagementException e) {
        handleExceptions(String.format(ErrorMessages.ERROR_WHILE_SETTING_IDP_DATA.getMessage(), tenantDomain), ErrorMessages.ERROR_WHILE_SETTING_IDP_DATA.getCode(), e);
    }
    if (residentIdP == null) {
        throw new PostAuthenticationFailedException(ErrorMessages.ERROR_WHILE_SETTING_IDP_DATA_IDP_IS_NULL.getCode(), String.format(ErrorMessages.ERROR_WHILE_SETTING_IDP_DATA_IDP_IS_NULL.getMessage(), tenantDomain));
    }
    if (StringUtils.isEmpty(receiptServiceInput.getService())) {
        if (log.isDebugEnabled()) {
            log.debug("No service name found. Hence adding resident IDP home realm ID");
        }
        receiptServiceInput.setService(residentIdP.getHomeRealmId());
    }
    if (StringUtils.isEmpty(receiptServiceInput.getTenantDomain())) {
        receiptServiceInput.setTenantDomain(tenantDomain);
    }
    if (StringUtils.isEmpty(receiptServiceInput.getSpDescription())) {
        if (StringUtils.isNotEmpty(residentIdP.getIdentityProviderDescription())) {
            receiptServiceInput.setSpDescription(residentIdP.getIdentityProviderDescription());
        } else {
            receiptServiceInput.setSpDescription(resideIdpDescription);
        }
    }
    if (StringUtils.isEmpty(receiptServiceInput.getSpDisplayName())) {
        if (StringUtils.isNotEmpty(residentIdP.getDisplayName())) {
            receiptServiceInput.setSpDisplayName(residentIdP.getDisplayName());
        } else {
            receiptServiceInput.setSpDisplayName(resideIdpDescription);
        }
    }
}
Also used : IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) IdentityProviderManager(org.wso2.carbon.idp.mgt.IdentityProviderManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 5 with PostAuthenticationFailedException

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

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