Search in sources :

Example 11 with PostAuthenticationFailedException

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

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

the class PostAuthAssociationHandler method handleRoleMapping.

private void handleRoleMapping(AuthenticationContext context, SequenceConfig sequenceConfig, Map<String, String> mappedAttrs) throws PostAuthenticationFailedException {
    String spRoleUri = DefaultSequenceHandlerUtils.getSpRoleClaimUri(sequenceConfig.getApplicationConfig());
    String[] roles;
    try {
        roles = DefaultSequenceHandlerUtils.getRolesFromSPMappedClaims(context, sequenceConfig, mappedAttrs, spRoleUri);
    } catch (FrameworkException e) {
        throw new PostAuthenticationFailedException(FrameworkErrorConstants.ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getCode(), FrameworkErrorConstants.ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getMessage(), e);
    }
    if (!ArrayUtils.isEmpty(roles)) {
        String spMappedUserRoles = DefaultSequenceHandlerUtils.getServiceProviderMappedUserRoles(sequenceConfig, Arrays.asList(roles));
        mappedAttrs.put(spRoleUri, spMappedUserRoles);
    }
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)

Example 13 with PostAuthenticationFailedException

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

the class PostAuthnMissingClaimHandler method handlePostAuthenticationForMissingClaimsResponse.

protected void handlePostAuthenticationForMissingClaimsResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
    if (log.isDebugEnabled()) {
        log.debug("Starting to process the response with missing claims");
    }
    Map<String, String> claims = new HashMap<String, String>();
    Map<String, String> claimsForContext = new HashMap<String, String>();
    Map<String, String[]> requestParams = request.getParameterMap();
    boolean persistClaims = false;
    AuthenticatedUser user = context.getSequenceConfig().getAuthenticatedUser();
    Map<String, String> carbonToSPClaimMapping = new HashMap<>();
    Object spToCarbonClaimMappingObject = context.getProperty(FrameworkConstants.SP_TO_CARBON_CLAIM_MAPPING);
    if (spToCarbonClaimMappingObject instanceof Map) {
        Map<String, String> spToCarbonClaimMapping = (Map<String, String>) spToCarbonClaimMappingObject;
        for (Map.Entry<String, String> entry : spToCarbonClaimMapping.entrySet()) {
            carbonToSPClaimMapping.put(entry.getValue(), entry.getKey());
        }
    }
    boolean doMandatoryClaimsExist = false;
    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
            doMandatoryClaimsExist = true;
            break;
        }
    }
    if (!doMandatoryClaimsExist) {
        // Check whether mandatory claims exist in the request. If not throw error.
        throw new PostAuthenticationFailedException("Mandatory missing claims are not found", "Mandatory missing " + "claims are not found in the request for the session with context identifier: " + context.getContextIdentifier());
    }
    List<String> missingClaims = new ArrayList<>();
    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
            String localClaimURI = entry.getKey().substring(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX.length());
            if (StringUtils.isBlank(entry.getValue()[0])) {
                missingClaims.add(localClaimURI);
                continue;
            }
            claims.put(localClaimURI, entry.getValue()[0]);
            if (spToCarbonClaimMappingObject != null) {
                String spClaimURI = carbonToSPClaimMapping.get(localClaimURI);
                claimsForContext.put(spClaimURI, entry.getValue()[0]);
            } else {
                claimsForContext.put(localClaimURI, entry.getValue()[0]);
            }
        }
    }
    if (CollectionUtils.isNotEmpty(missingClaims)) {
        String missingClaimURIs = StringUtils.join(missingClaims, ",");
        if (log.isDebugEnabled()) {
            log.debug("Claim values for the mandatory claims: " + missingClaimURIs + " are empty");
        }
        throw new PostAuthenticationFailedException("Mandatory claim is not found", "Claim " + "values for the claim URIs: " + missingClaimURIs + " are empty");
    }
    Map<ClaimMapping, String> authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(claimsForContext);
    authenticatedUserAttributes.putAll(user.getUserAttributes());
    for (Map.Entry<Integer, StepConfig> entry : context.getSequenceConfig().getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        if (stepConfig.isSubjectAttributeStep()) {
            if (stepConfig.getAuthenticatedUser() != null) {
                user = stepConfig.getAuthenticatedUser();
            }
            if (!user.isFederatedUser()) {
                persistClaims = true;
            } else {
                String associatedID;
                String subject = user.getAuthenticatedSubjectIdentifier();
                try {
                    FederatedAssociationManager federatedAssociationManager = FrameworkUtils.getFederatedAssociationManager();
                    associatedID = federatedAssociationManager.getUserForFederatedAssociation(context.getTenantDomain(), stepConfig.getAuthenticatedIdP(), subject);
                    if (StringUtils.isNotBlank(associatedID)) {
                        String fullQualifiedAssociatedUserId = FrameworkUtils.prependUserStoreDomainToName(associatedID + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
                        UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedID));
                        user = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(fullQualifiedAssociatedUserId);
                        persistClaims = true;
                    }
                } catch (FederatedAssociationManagerException | FrameworkException e) {
                    throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while getting association for " + subject, e);
                }
            }
            break;
        }
    }
    if (persistClaims) {
        if (log.isDebugEnabled()) {
            log.debug("Local user mapping found. Claims will be persisted");
        }
        try {
            Map<String, String> claimMapping = context.getSequenceConfig().getApplicationConfig().getClaimMappings();
            Map<String, String> localIdpClaims = new HashMap<>();
            for (Map.Entry<String, String> entry : claims.entrySet()) {
                String localClaim = claimMapping.get(entry.getKey());
                localIdpClaims.put(localClaim, entry.getValue());
            }
            if (log.isDebugEnabled()) {
                log.debug("Updating user profile of user : " + user.getLoggableUserId());
            }
            UserRealm realm = getUserRealm(user.getTenantDomain());
            AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) realm.getUserStoreManager();
            userStoreManager.setUserClaimValuesWithID(user.getUserId(), localIdpClaims, null);
        } catch (UserStoreException e) {
            if (e instanceof UserStoreClientException) {
                context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR, e.getMessage());
                if (StringUtils.isNotBlank(e.getErrorCode())) {
                    context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE, e.getErrorCode());
                }
                /*
                    When the attribute update is disabled for JIT provisioned users, the mandatory claim update
                    request will be identified through the error code and handled it.
                     */
                if (ERROR_CODE_INVALID_ATTRIBUTE_UPDATE.equals(e.getErrorCode())) {
                    context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
                    return;
                }
            }
            if (ErrorMessages.ERROR_CODE_READONLY_USER_STORE.getCode().equals(e.getErrorCode())) {
                context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
                return;
            }
            throw new PostAuthenticationFailedException(e.getMessage(), "Error while updating claims for local user. Could not update profile", e);
        } catch (UserIdNotFoundException e) {
            throw new PostAuthenticationFailedException("User id not found", "User id not found for local user. Could not update profile", e);
        }
    }
    context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
}
Also used : HashMap(java.util.HashMap) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) ArrayList(java.util.ArrayList) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) FederatedAssociationManager(org.wso2.carbon.identity.user.profile.mgt.association.federation.FederatedAssociationManager) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) FederatedAssociationManagerException(org.wso2.carbon.identity.user.profile.mgt.association.federation.exception.FederatedAssociationManagerException) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) Map(java.util.Map) HashMap(java.util.HashMap)

Example 14 with PostAuthenticationFailedException

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

the class PostAuthnMissingClaimHandler method handlePostAuthenticationForMissingClaimsRequest.

protected PostAuthnHandlerFlowStatus handlePostAuthenticationForMissingClaimsRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
    String[] missingClaims = FrameworkUtils.getMissingClaims(context);
    if (StringUtils.isNotBlank(missingClaims[0])) {
        if (log.isDebugEnabled()) {
            log.debug("Mandatory claims missing for the application : " + missingClaims[0]);
        }
        try {
            // If there are read only claims marked as mandatory and they are missing, we cannot proceed further.
            // We have to end the flow and show an error message to user.
            ClaimManager claimManager = getUserRealm(context.getTenantDomain()).getClaimManager();
            Map<String, String> missingClaimMap = FrameworkUtils.getMissingClaimsMap(context);
            for (Map.Entry<String, String> missingClaim : missingClaimMap.entrySet()) {
                Claim claimObj = claimManager.getClaim(missingClaim.getValue());
                if (claimObj != null && claimObj.isReadOnly()) {
                    throw new PostAuthenticationFailedException("One or more read-only claim is missing in the " + "requested claim set. Please contact your administrator for more information about " + "this issue.", "One or more read-only claim is missing in the requested claim set");
                }
            }
            List<LocalClaim> localClaims = getClaimMetadataManagementService().getLocalClaims(context.getTenantDomain());
            String displayNames = getMissingClaimsDisplayNames(missingClaimMap, localClaims);
            URIBuilder uriBuilder = new URIBuilder(ConfigurationFacade.getInstance().getAuthenticationEndpointMissingClaimsURL());
            uriBuilder.addParameter(FrameworkConstants.MISSING_CLAIMS, missingClaims[0]);
            uriBuilder.addParameter(FrameworkConstants.DISPLAY_NAMES, displayNames);
            uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());
            uriBuilder.addParameter(FrameworkConstants.REQUEST_PARAM_SP, context.getSequenceConfig().getApplicationConfig().getApplicationName());
            if (context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR) != null) {
                uriBuilder.addParameter("errorMessage", context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR).toString());
                context.removeProperty(POST_AUTH_MISSING_CLAIMS_ERROR);
            }
            if (context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE) != null) {
                uriBuilder.addParameter("errorCode", context.getProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE).toString());
                context.removeProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE);
            }
            response.sendRedirect(uriBuilder.build().toString());
            context.setProperty(POST_AUTHENTICATION_REDIRECTION_TRIGGERED, true);
            if (log.isDebugEnabled()) {
                log.debug("Redirecting to outside to pick mandatory claims");
            }
        } catch (IOException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error " + "while redirecting to request claims page", e);
        } catch (URISyntaxException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while building redirect URI", e);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while retrieving claim from claim URI.", e);
        } catch (ClaimMetadataException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while retrieving claim metadata.", e);
        }
        return PostAuthnHandlerFlowStatus.INCOMPLETE;
    } else {
        return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED;
    }
}
Also used : ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) LocalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder) ClaimManager(org.wso2.carbon.user.api.ClaimManager) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) Map(java.util.Map) HashMap(java.util.HashMap) LocalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim) Claim(org.wso2.carbon.user.api.Claim)

Example 15 with PostAuthenticationFailedException

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

the class ConsentMgtPostAuthnHandler method handlePreConsent.

protected PostAuthnHandlerFlowStatus handlePreConsent(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
    String spName = context.getSequenceConfig().getApplicationConfig().getApplicationName();
    Map<String, String> claimMappings = context.getSequenceConfig().getApplicationConfig().getClaimMappings();
    // Should be removed once the issue is fixed
    if (SP_NAME_DEFAULT.equalsIgnoreCase(spName)) {
        return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED;
    }
    AuthenticatedUser authenticatedUser = getAuthenticatedUser(context);
    ServiceProvider serviceProvider = getServiceProvider(context);
    try {
        ConsentClaimsData consentClaimsData = getSSOConsentService().getConsentRequiredClaimsWithExistingConsents(serviceProvider, authenticatedUser);
        if (isDebugEnabled()) {
            String message = String.format("Retrieving required consent data of user: %s for service " + "provider: %s in tenant domain: %s.", authenticatedUser.getAuthenticatedSubjectIdentifier(), serviceProvider.getApplicationName(), getSPTenantDomain(serviceProvider));
            logDebug(message);
        }
        removeClaimsWithoutConsent(context, consentClaimsData);
        // Remove the claims which dont have values given by the user.
        consentClaimsData.setRequestedClaims(removeConsentRequestedNullUserAttributes(consentClaimsData.getRequestedClaims(), authenticatedUser.getUserAttributes(), claimMappings));
        if (hasConsentForRequiredClaims(consentClaimsData)) {
            if (isDebugEnabled()) {
                String message = String.format("Required consent data is empty for user: %s for service " + "provider: %s in tenant domain: %s. Post authentication completed.", authenticatedUser.getAuthenticatedSubjectIdentifier(), serviceProvider.getApplicationName(), getSPTenantDomain(serviceProvider));
                logDebug(message);
            }
            return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED;
        } else {
            String mandatoryLocalClaims = buildConsentClaimString(consentClaimsData.getMandatoryClaims());
            String requestedLocalClaims = buildConsentClaimString(consentClaimsData.getRequestedClaims());
            if (isDebugEnabled()) {
                String message = "Require consent for mandatory claims: %s, requested claims: %s, from user: %s " + "for service provider: %s in tenant domain: %s.";
                message = String.format(message, consentClaimsData.getMandatoryClaims(), consentClaimsData.getRequestedClaims(), authenticatedUser.getAuthenticatedSubjectIdentifier(), serviceProvider.getApplicationName(), getSPTenantDomain(serviceProvider));
                logDebug(message);
            }
            redirectToConsentPage(response, context, requestedLocalClaims, mandatoryLocalClaims);
            setConsentPoppedUpState(context);
            context.addParameter(CONSENT_CLAIM_META_DATA, consentClaimsData);
            return PostAuthnHandlerFlowStatus.INCOMPLETE;
        }
    } catch (SSOConsentDisabledException e) {
        return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED;
    } catch (SSOConsentServiceException e) {
        String error = String.format("Error occurred while retrieving consent data of user: %s for service " + "provider: %s in tenant domain: %s.", authenticatedUser.getAuthenticatedSubjectIdentifier(), serviceProvider.getApplicationName(), getSPTenantDomain(serviceProvider));
        throw new PostAuthenticationFailedException("Authentication failed. Error occurred while processing user " + "consent.", error, e);
    }
}
Also used : SSOConsentDisabledException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentDisabledException) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) SSOConsentServiceException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException) StringUtils.defaultString(org.apache.commons.lang.StringUtils.defaultString) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

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