Search in sources :

Example 16 with PostAuthenticationFailedException

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

the class ConsentMgtPostAuthnHandler method getSPRequestedLocalClaims.

private List<String> getSPRequestedLocalClaims(AuthenticationContext context) throws PostAuthenticationFailedException {
    List<String> spRequestedLocalClaims = new ArrayList<>();
    ApplicationConfig applicationConfig = context.getSequenceConfig().getApplicationConfig();
    if (applicationConfig == null) {
        ServiceProvider serviceProvider = getServiceProvider(context);
        String error = "Application configs are null in AuthenticationContext for SP: " + serviceProvider.getApplicationName() + " in tenant domain: " + getSPTenantDomain(serviceProvider);
        throw new PostAuthenticationFailedException("Authentication failed. Error while processing application " + "claim configurations.", error);
    }
    Map<String, String> claimMappings = applicationConfig.getRequestedClaimMappings();
    if (isNotEmpty(claimMappings) && isNotEmpty(claimMappings.values())) {
        spRequestedLocalClaims = new ArrayList<>(claimMappings.values());
    }
    String subjectClaimUri = getSubjectClaimUri(applicationConfig);
    spRequestedLocalClaims.remove(subjectClaimUri);
    if (isDebugEnabled()) {
        String message = String.format("Requested claims for SP: %s - " + spRequestedLocalClaims, applicationConfig.getApplicationName());
        logDebug(message);
    }
    return spRequestedLocalClaims;
}
Also used : ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ArrayList(java.util.ArrayList) StringUtils.defaultString(org.apache.commons.lang.StringUtils.defaultString) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)

Example 17 with PostAuthenticationFailedException

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

the class ConsentMgtPostAuthnHandler method removeDisapprovedClaims.

private void removeDisapprovedClaims(AuthenticationContext context, AuthenticatedUser authenticatedUser) throws SSOConsentServiceException, PostAuthenticationFailedException {
    String spStandardDialect = getStandardDialect(context);
    List<String> claimWithConsent = getClaimsFromMetaData(getSSOConsentService().getClaimsWithConsents(getServiceProvider(context), authenticatedUser));
    List<String> disapprovedClaims = getClaimsWithoutConsent(claimWithConsent, context);
    if (isDebugEnabled()) {
        String message = "Removing disapproved claims: %s in the dialect: %s by user: %s for service provider: %s" + " in tenant domain: %s.";
        ServiceProvider serviceProvider = getServiceProvider(context);
        message = String.format(message, disapprovedClaims, defaultString(spStandardDialect), getAuthenticatedUser(context).getAuthenticatedSubjectIdentifier(), serviceProvider.getApplicationName(), getSPTenantDomain(serviceProvider));
        logDebug(message);
    }
    removeUserClaimsFromContext(context, disapprovedClaims, spStandardDialect);
}
Also used : ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) StringUtils.defaultString(org.apache.commons.lang.StringUtils.defaultString)

Example 18 with PostAuthenticationFailedException

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

the class DefaultRequestCoordinator method handle.

@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    CommonAuthResponseWrapper responseWrapper = null;
    if (response instanceof CommonAuthResponseWrapper) {
        responseWrapper = (CommonAuthResponseWrapper) response;
    } else {
        responseWrapper = new CommonAuthResponseWrapper(response);
        responseWrapper.setWrappedByFramework(true);
    }
    AuthenticationContext context = null;
    String sessionDataKey = request.getParameter("sessionDataKey");
    try {
        AuthenticationRequestCacheEntry authRequest = null;
        boolean returning = false;
        // TODO: use a different mechanism to determine the flow start.
        if (request.getParameter("type") != null) {
            // handles common auth logout request.
            if (sessionDataKey != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieving authentication request from cache for the sessionDataKey: " + sessionDataKey);
                }
                authRequest = getAuthenticationRequest(request, sessionDataKey);
                if (authRequest == null) {
                    // authRequest is not retrieved from the cache.
                    if (log.isDebugEnabled()) {
                        log.debug("No authentication request found in the cache for sessionDataKey: " + sessionDataKey);
                    }
                    if (isCommonAuthLogoutRequest(request)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Ignoring the invalid sessionDataKey: " + sessionDataKey + " in the " + "CommonAuthLogout request.");
                        }
                    } else {
                        throw new FrameworkException("Invalid authentication request with sessionDataKey: " + sessionDataKey);
                    }
                }
            } else if (!isCommonAuthLogoutRequest(request)) {
                // sessionDataKey is null and not a common auth logout request
                if (log.isDebugEnabled()) {
                    log.debug("Session data key is null in the request and not a logout request.");
                }
                FrameworkUtils.sendToRetryPage(request, response, context);
            }
            // if there is a cache entry, wrap the original request with params in cache entry
            if (authRequest != null) {
                request = FrameworkUtils.getCommonAuthReqWithParams(request, authRequest);
            }
            context = initializeFlow(request, responseWrapper);
            context.initializeAnalyticsData();
        } else {
            returning = true;
            context = FrameworkUtils.getContextData(request);
            associateTransientRequestData(request, responseWrapper, context);
        }
        if (context != null) {
            if (StringUtils.isNotBlank(context.getServiceProviderName())) {
                MDC.put(SERVICE_PROVIDER_QUERY_KEY, context.getServiceProviderName());
            }
            // different threads.
            synchronized (context) {
                if (!context.isActiveInAThread()) {
                    // Marks this context is active in a thread. We only allow at a single instance, a context
                    // to be active in only a single thread. In other words, same context cannot active in two
                    // different threads at the same time.
                    context.setActiveInAThread(true);
                    if (log.isDebugEnabled()) {
                        log.debug("Context id: " + context.getContextIdentifier() + " is active in the thread " + "with id: " + Thread.currentThread().getId());
                    }
                } else {
                    log.error("Same context is currently in used by a different thread. Possible double submit.");
                    if (log.isDebugEnabled()) {
                        log.debug("Same context is currently in used by a different thread. Possible double submit." + "\n" + "Context id: " + context.getContextIdentifier() + "\n" + "Originating address: " + request.getRemoteAddr() + "\n" + "Request Headers: " + getHeaderString(request) + "\n" + "Thread Id: " + Thread.currentThread().getId());
                    }
                    FrameworkUtils.sendToRetryPage(request, responseWrapper, context);
                    return;
                }
            }
            /*
                If
                 Request specify to restart the flow again from first step by passing `restart_flow`.
                 OR
                 Identifier first request received and current step does not contains any flow handler.
                    (To handle browser back with only with identifier-first and basic)
                */
            if (isBackToFirstStepRequest(request) || (isIdentifierFirstRequest(request) && !isFlowHandlerInCurrentStepCanHandleRequest(context, request))) {
                if (isCompletedStepsAreFlowHandlersOnly(context)) {
                    // authenticated authenticator, then we reset the current step to 1.
                    if (log.isDebugEnabled()) {
                        log.debug("Restarting the authentication flow from step 1 for  " + context.getContextIdentifier());
                    }
                    context.setCurrentStep(0);
                    context.setProperty(BACK_TO_FIRST_STEP, true);
                    Map<String, String> runtimeParams = context.getAuthenticatorParams(FrameworkConstants.JSAttributes.JS_COMMON_OPTIONS);
                    runtimeParams.put(FrameworkConstants.JSAttributes.JS_OPTIONS_USERNAME, null);
                    FrameworkUtils.resetAuthenticationContext(context);
                    returning = false;
                    // IDF should be the first step.
                    context.getCurrentAuthenticatedIdPs().clear();
                } else {
                    // If the incoming request is restart and the completed steps have authenticators as the
                    // authenticated authenticator, then we redirect to retry page.
                    String msg = "Restarting the authentication flow failed because there is/are authenticator/s " + "available in the completed steps for  " + context.getContextIdentifier();
                    if (log.isDebugEnabled()) {
                        log.debug(msg);
                    }
                    throw new MisconfigurationException(msg);
                }
            }
            setSPAttributeToRequest(request, context);
            context.setReturning(returning);
            // if this is the flow start, store the original request in the context
            if (!context.isReturning() && authRequest != null) {
                context.setAuthenticationRequest(authRequest.getAuthenticationRequest());
            }
            if (!context.isLogoutRequest()) {
                FrameworkUtils.getAuthenticationRequestHandler().handle(request, responseWrapper, context);
            } else {
                FrameworkUtils.getLogoutRequestHandler().handle(request, responseWrapper, context);
            }
        } else {
            if (log.isDebugEnabled()) {
                String key = request.getParameter("sessionDataKey");
                if (key == null) {
                    log.debug("Session data key is null in the request");
                } else {
                    log.debug("Session data key  :  " + key);
                }
            }
            String userAgent = request.getHeader("User-Agent");
            String referer = request.getHeader("Referer");
            String message = "Requested client: " + request.getRemoteAddr() + ", URI :" + request.getMethod() + ":" + request.getRequestURI() + ", User-Agent: " + userAgent + " , Referer: " + referer;
            log.error("Context does not exist. Probably due to invalidated cache. " + message);
            FrameworkUtils.sendToRetryPage(request, responseWrapper, context);
        }
    } catch (JsFailureException e) {
        if (log.isDebugEnabled()) {
            log.debug("Script initiated Exception occured.", e);
        }
        publishAuthenticationFailure(request, context, context.getSequenceConfig().getAuthenticatedUser(), e.getErrorCode());
        if (log.isDebugEnabled()) {
            log.debug("User will be redirected to retry page or the error page provided by script.");
        }
    } catch (MisconfigurationException e) {
        FrameworkUtils.sendToRetryPage(request, responseWrapper, context, "misconfiguration.error", "something.went.wrong.contact.admin");
    } catch (PostAuthenticationFailedException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while evaluating post authentication", e);
        }
        FrameworkUtils.removeCookie(request, responseWrapper, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()));
        publishAuthenticationFailure(request, context, context.getSequenceConfig().getAuthenticatedUser(), e.getErrorCode());
        FrameworkUtils.sendToRetryPage(request, responseWrapper, context, "authentication.attempt.failed", "authorization.failed");
    } catch (Throwable e) {
        if ((e instanceof FrameworkException) && (NONCE_ERROR_CODE.equals(((FrameworkException) e).getErrorCode()))) {
            if (log.isDebugEnabled()) {
                log.debug(e.getMessage(), e);
            }
            FrameworkUtils.sendToRetryPage(request, response, context, "suspicious.authentication.attempts", "suspicious.authentication.attempts.description");
        } else {
            log.error("Exception in Authentication Framework", e);
            FrameworkUtils.sendToRetryPage(request, responseWrapper, context);
        }
    } finally {
        UserCoreUtil.setDomainInThreadLocal(null);
        if (context != null) {
            // Mark this context left the thread. Now another thread can use this context.
            context.setActiveInAThread(false);
            if (log.isDebugEnabled()) {
                log.debug("Context id: " + context.getContextIdentifier() + " left the thread with id: " + Thread.currentThread().getId());
            }
            // If flow is not about to conclude.
            if (!LoginContextManagementUtil.isPostAuthenticationExtensionCompleted(context) || context.isLogoutRequest()) {
                // Persist the context.
                FrameworkUtils.addAuthenticationContextToCache(context.getContextIdentifier(), context);
                if (log.isDebugEnabled()) {
                    log.debug("Context with id: " + context.getContextIdentifier() + " added to the cache.");
                }
            }
            // Clear the auto login related cookies only during none passive authentication flow.
            if (!context.isPassiveAuthenticate()) {
                FrameworkUtils.removeALORCookie(request, response);
            }
        }
        unwrapResponse(responseWrapper, sessionDataKey, response, context);
    }
}
Also used : AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) MisconfigurationException(org.wso2.carbon.identity.application.authentication.framework.exception.MisconfigurationException) JsFailureException(org.wso2.carbon.identity.application.authentication.framework.exception.JsFailureException) PostAuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException) AuthenticationRequestCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 19 with PostAuthenticationFailedException

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

the class JITProvisioningPostAuthenticationHandler method handleConsents.

/**
 * This method is responsible for handling consents.
 *
 * @param request      Relevant http servlet request.
 * @param stepConfig   Step Configuration for the particular configuration step.
 * @param tenantDomain Specific tenant domain.
 * @throws PostAuthenticationFailedException Post Authentication failed exception.
 */
private void handleConsents(HttpServletRequest request, StepConfig stepConfig, String tenantDomain) throws PostAuthenticationFailedException {
    String userName = getLocalUserAssociatedForFederatedIdentifier(stepConfig.getAuthenticatedIdP(), stepConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier(), tenantDomain);
    String consent = request.getParameter("consent");
    String policyURL = request.getParameter("policy");
    if (StringUtils.isNotEmpty(consent)) {
        ReceiptInput receiptInput = buildConsentForResidentIDP(userName, consent, policyURL);
        addConsent(receiptInput, tenantDomain);
    }
}
Also used : ReceiptInput(org.wso2.carbon.consent.mgt.core.model.ReceiptInput)

Example 20 with PostAuthenticationFailedException

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

the class JITProvisioningPostAuthenticationHandler method getCombinedClaims.

/**
 * To get the final claims that need to be stored against user by combining the claims from IDP as well as from
 * User entered claims.
 *
 * @param request          Http servlet request.
 * @param localClaimValues Relevant local claim values from IDP.
 * @param context          AuthenticationContext.
 * @return combination of claims came from IDP and the claims user has filed.
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private Map<String, String> getCombinedClaims(HttpServletRequest request, Map<String, String> localClaimValues, AuthenticationContext context) throws PostAuthenticationFailedException {
    String externalIdPConfigName = context.getExternalIdP().getIdPName();
    org.wso2.carbon.user.api.ClaimMapping[] claims = getClaimsForTenant(context.getTenantDomain(), externalIdPConfigName);
    Map<String, String> missingClaims = new HashMap<>();
    if (claims != null) {
        for (org.wso2.carbon.user.api.ClaimMapping claimMapping : claims) {
            String uri = claimMapping.getClaim().getClaimUri();
            String claimValue = request.getParameter(uri);
            if (StringUtils.isNotBlank(claimValue) && StringUtils.isEmpty(localClaimValues.get(uri))) {
                localClaimValues.put(uri, claimValue);
            } else {
                /* Claims that are mandatory from service provider level will pre-appended with "missing-" in
                     there name.
                     */
                claimValue = request.getParameter("missing-" + uri);
                if (StringUtils.isNotEmpty(claimValue)) {
                    localClaimValues.put(uri, claimValue);
                    missingClaims.put(uri, claimValue);
                }
            }
        }
    }
    // Handle the missing claims.
    if (MapUtils.isNotEmpty(missingClaims)) {
        AuthenticatedUser authenticatedUser = context.getSequenceConfig().getAuthenticatedUser();
        Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
        userAttributes.putAll(FrameworkUtils.buildClaimMappings(missingClaims));
        authenticatedUser.setUserAttributes(userAttributes);
        context.getSequenceConfig().setAuthenticatedUser(authenticatedUser);
    }
    return localClaimValues;
}
Also used : HashMap(java.util.HashMap) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping)

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