Search in sources :

Example 1 with MisconfigurationException

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

the class DefaultStepBasedSequenceHandler method handlePostAuthentication.

@SuppressWarnings("unchecked")
protected void handlePostAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
    if (log.isDebugEnabled()) {
        log.debug("Handling Post Authentication tasks");
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    StringBuilder jsonBuilder = new StringBuilder();
    boolean subjectFoundInStep = false;
    boolean subjectAttributesFoundInStep = false;
    int stepCount = 1;
    Map<String, String> mappedAttrs = new HashMap<>();
    Map<ClaimMapping, String> authenticatedUserAttributes = new HashMap<>();
    boolean isAuthenticatorExecuted = false;
    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 AuthenticationFlowHandler)) {
            isAuthenticatorExecuted = true;
        }
        // build the authenticated idps JWT to send to the calling servlet.
        if (stepCount == 1) {
            jsonBuilder.append("\"idps\":");
            jsonBuilder.append("[");
        }
        // build the JSON object for this step
        jsonBuilder.append("{");
        jsonBuilder.append("\"idp\":\"").append(stepConfig.getAuthenticatedIdP()).append("\",");
        jsonBuilder.append("\"authenticator\":\"").append(authenticator.getName()).append("\"");
        if (stepCount != sequenceConfig.getStepMap().size()) {
            jsonBuilder.append("},");
        } else {
            // wrap up the JSON object
            jsonBuilder.append("}");
            jsonBuilder.append("]");
            sequenceConfig.setAuthenticatedIdPs(IdentityApplicationManagementUtil.getSignedJWT(jsonBuilder.toString(), sequenceConfig.getApplicationConfig().getServiceProvider()));
            stepConfig.setSubjectIdentifierStep(!subjectFoundInStep);
            stepConfig.setSubjectAttributeStep(!subjectAttributesFoundInStep);
        }
        stepCount++;
        if (authenticator instanceof FederatedApplicationAuthenticator) {
            ExternalIdPConfig externalIdPConfig = null;
            try {
                externalIdPConfig = ConfigurationFacade.getInstance().getIdPConfigByName(stepConfig.getAuthenticatedIdP(), context.getTenantDomain());
            } catch (IdentityProviderManagementException e) {
                log.error("Exception while getting IdP by name", e);
            }
            context.setExternalIdP(externalIdPConfig);
            String originalExternalIdpSubjectValueForThisStep = stepConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier();
            if (externalIdPConfig == null) {
                String errorMsg = "An External IdP cannot be null for a FederatedApplicationAuthenticator";
                log.error(errorMsg);
                throw new FrameworkException(errorMsg);
            }
            Map<ClaimMapping, String> extAttrs;
            Map<String, String> extAttibutesValueMap;
            Map<String, String> localClaimValues = null;
            Map<String, String> idpClaimValues = null;
            extAttrs = stepConfig.getAuthenticatedUser().getUserAttributes();
            extAttibutesValueMap = FrameworkUtils.getClaimMappings(extAttrs, false);
            if (stepConfig.isSubjectAttributeStep()) {
                subjectAttributesFoundInStep = true;
                String idpRoleClaimUri = getIdpRoleClaimUri(stepConfig, context);
                // Get the mapped user roles according to the mapping in the IDP configuration.
                // Include the unmapped roles as it is.
                List<String> identityProviderMappedUserRolesUnmappedInclusive = getIdentityProvideMappedUserRoles(externalIdPConfig, extAttibutesValueMap, idpRoleClaimUri, returnOnlyMappedLocalRoles);
                String serviceProviderMappedUserRoles = getServiceProviderMappedUserRoles(sequenceConfig, identityProviderMappedUserRolesUnmappedInclusive);
                if (StringUtils.isNotBlank(idpRoleClaimUri) && StringUtils.isNotBlank(serviceProviderMappedUserRoles)) {
                    extAttibutesValueMap.put(idpRoleClaimUri, serviceProviderMappedUserRoles);
                }
                if (mappedAttrs == null || mappedAttrs.isEmpty()) {
                    // do claim handling
                    mappedAttrs = handleClaimMappings(stepConfig, context, extAttibutesValueMap, true);
                    // external claim values mapped to local claim uris.
                    localClaimValues = (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
                    idpClaimValues = (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_IDP_CLAIM_VALUES);
                }
            }
            if (stepConfig.isSubjectIdentifierStep()) {
                if (!stepConfig.isSubjectAttributeStep()) {
                    /*
                        Do claim mapping inorder to get subject claim uri requested. This is done only if the
                        step is not a subject attribute step. Because it is already done in the previous flow if
                        the step is a subject attribute step.
                        */
                    handleClaimMappings(stepConfig, context, extAttibutesValueMap, true);
                }
                subjectFoundInStep = true;
                sequenceConfig.setAuthenticatedUser(new AuthenticatedUser(stepConfig.getAuthenticatedUser()));
            }
            if (stepConfig.isSubjectAttributeStep()) {
                if (!sequenceConfig.getApplicationConfig().isMappedSubjectIDSelected()) {
                    // if we found the mapped subject - then we do not need to worry about
                    // finding attributes.
                    // if no requested claims are selected and sp claim dialect is not a standard dialect,
                    // send all local mapped claim values or idp claim values
                    ApplicationConfig appConfig = context.getSequenceConfig().getApplicationConfig();
                    if (MapUtils.isEmpty(appConfig.getRequestedClaimMappings()) && !isSPStandardClaimDialect(context.getRequestType())) {
                        if (MapUtils.isNotEmpty(localClaimValues)) {
                            mappedAttrs = localClaimValues;
                        } else if (MapUtils.isNotEmpty(idpClaimValues)) {
                            mappedAttrs = idpClaimValues;
                        }
                    }
                    authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(mappedAttrs);
                }
            }
        } else {
            if (stepConfig.isSubjectIdentifierStep()) {
                if (!stepConfig.isSubjectAttributeStep()) {
                    /*
                        Do claim mapping inorder to get subject claim uri requested. This is done only if the
                        step is not a subject attribute step. Because it is already done in the previous flow if
                        the step is a subject attribute step.
                        */
                    handleClaimMappings(stepConfig, context, null, false);
                }
                subjectFoundInStep = true;
                sequenceConfig.setAuthenticatedUser(new AuthenticatedUser(stepConfig.getAuthenticatedUser()));
                if (log.isDebugEnabled()) {
                    log.debug("Authenticated User: " + sequenceConfig.getAuthenticatedUser().getLoggableUserId());
                    log.debug("Authenticated User Tenant Domain: " + sequenceConfig.getAuthenticatedUser().getTenantDomain());
                }
            }
            if (stepConfig.isSubjectAttributeStep()) {
                subjectAttributesFoundInStep = true;
                // local authentications
                mappedAttrs = handleClaimMappings(stepConfig, context, null, false);
                handleRoleMapping(context, sequenceConfig, mappedAttrs);
                authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(mappedAttrs);
            }
        }
    }
    if (!isAuthenticatorExecuted) {
        String errorMsg = String.format("No authenticator have been executed in the authentication flow of " + "application: %s in tenant-domain: %s", sequenceConfig.getApplicationConfig().getApplicationName(), context.getTenantDomain());
        log.error(errorMsg);
        throw new MisconfigurationException(errorMsg);
    }
    if (isSPStandardClaimDialect(context.getRequestType()) && authenticatedUserAttributes.isEmpty() && sequenceConfig.getAuthenticatedUser() != null) {
        sequenceConfig.getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
    }
    if (!authenticatedUserAttributes.isEmpty() && sequenceConfig.getAuthenticatedUser() != null) {
        sequenceConfig.getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
    }
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) HashMap(java.util.HashMap) MisconfigurationException(org.wso2.carbon.identity.application.authentication.framework.exception.MisconfigurationException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) 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) ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig) AuthenticationFlowHandler(org.wso2.carbon.identity.application.authentication.framework.AuthenticationFlowHandler) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) HashMap(java.util.HashMap) Map(java.util.Map) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 2 with MisconfigurationException

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

Aggregations

FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)2 MisconfigurationException (org.wso2.carbon.identity.application.authentication.framework.exception.MisconfigurationException)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator)1 AuthenticationFlowHandler (org.wso2.carbon.identity.application.authentication.framework.AuthenticationFlowHandler)1 FederatedApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator)1 AuthenticationRequestCacheEntry (org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry)1 ApplicationConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig)1 AuthenticatorConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig)1 ExternalIdPConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig)1 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)1 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)1 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)1 JsFailureException (org.wso2.carbon.identity.application.authentication.framework.exception.JsFailureException)1 PostAuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException)1 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)1 CommonAuthResponseWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)1 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)1 IdentityProviderManagementException (org.wso2.carbon.idp.mgt.IdentityProviderManagementException)1