Search in sources :

Example 1 with AuthenticatedIdPData

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData in project carbon-identity-framework by wso2.

the class DefaultStepHandler method handle.

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
    if (context.getAnalyticsData(FrameworkConstants.AnalyticsData.CURRENT_AUTHENTICATOR_START_TIME) == null) {
        context.setAnalyticsData(FrameworkConstants.AnalyticsData.CURRENT_AUTHENTICATOR_START_TIME, System.currentTimeMillis());
    }
    StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(context.getCurrentStep());
    List<AuthenticatorConfig> authConfigList = stepConfig.getAuthenticatorList();
    String authenticatorNames = FrameworkUtils.getAuthenticatorIdPMappingString(authConfigList);
    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();
    String fidp = request.getParameter(FrameworkConstants.RequestParams.FEDERATED_IDP);
    Map<String, AuthenticatedIdPData> authenticatedIdPs = context.getCurrentAuthenticatedIdPs();
    // NOTE : currentAuthenticatedIdPs (if not null) always contains the previousAuthenticatedIdPs
    if (MapUtils.isEmpty(authenticatedIdPs)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No current authenticated IDPs in the authentication context. " + "Continuing with the previous authenticated IDPs");
        }
        authenticatedIdPs = context.getPreviousAuthenticatedIdPs();
    }
    if (LOG.isDebugEnabled()) {
        if (MapUtils.isEmpty(authenticatedIdPs)) {
            LOG.debug("No previous authenticated IDPs found in the authentication context.");
        } else {
            LOG.debug(String.format("Found authenticated IdPs. Count: %d", authenticatedIdPs.size()));
        }
    }
    if (context.isPassiveAuthenticate() && MapUtils.isNotEmpty(context.getAuthenticatedIdPsOfApp())) {
        authenticatedIdPs = context.getAuthenticatedIdPsOfApp();
    }
    Map<String, AuthenticatorConfig> authenticatedStepIdps = FrameworkUtils.getAuthenticatedStepIdPs(stepConfig, authenticatedIdPs);
    // check passive authentication
    if (context.isPassiveAuthenticate()) {
        if (authenticatedStepIdps.isEmpty()) {
            context.setRequestAuthenticated(false);
        } else {
            String authenticatedIdP = authenticatedStepIdps.entrySet().iterator().next().getKey();
            AuthenticatedIdPData authenticatedIdPData = authenticatedIdPs.get(authenticatedIdP);
            populateStepConfigWithAuthenticationDetails(stepConfig, authenticatedIdPData, authenticatedStepIdps.get(authenticatedIdP));
            request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
        }
        stepConfig.setCompleted(true);
        return;
    } else {
        long authTime = 0;
        String maxAgeParam = request.getParameter(FrameworkConstants.RequestParams.MAX_AGE);
        if (StringUtils.isNotBlank(maxAgeParam) && StringUtils.isNotBlank(context.getSessionIdentifier())) {
            String loginTenantDomain = context.getLoginTenantDomain();
            long maxAge = Long.parseLong((maxAgeParam));
            if (FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), loginTenantDomain).getProperty(FrameworkConstants.UPDATED_TIMESTAMP) != null) {
                authTime = Long.parseLong(FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), loginTenantDomain).getProperty(FrameworkConstants.UPDATED_TIMESTAMP).toString());
            } else {
                authTime = Long.parseLong(FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), loginTenantDomain).getProperty(FrameworkConstants.CREATED_TIMESTAMP).toString());
            }
            long currentTime = System.currentTimeMillis();
            if (maxAge < (currentTime - authTime) / 1000) {
                context.setForceAuthenticate(true);
            } else {
                context.setPreviousAuthTime(true);
            }
        }
    }
    if (request.getParameter(FrameworkConstants.RequestParams.USER_ABORT) != null && Boolean.parseBoolean(request.getParameter(FrameworkConstants.RequestParams.USER_ABORT))) {
        request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.USER_ABORT);
        stepConfig.setCompleted(true);
        return;
    }
    // if Request has fidp param and if this is the first step
    if (fidp != null && stepConfig.getOrder() == 1) {
        handleHomeRealmDiscovery(request, response, context);
        return;
    } else if (context.isReturning()) {
        // if this is a request from the multi-option page
        if (request.getParameter(FrameworkConstants.RequestParams.AUTHENTICATOR) != null && !request.getParameter(FrameworkConstants.RequestParams.AUTHENTICATOR).isEmpty()) {
            handleRequestFromLoginPage(request, response, context);
            return;
        } else {
            // if this is a response from external parties (e.g. federated IdPs)
            handleResponse(request, response, context);
            return;
        }
    } else if (ConfigurationFacade.getInstance().isDumbMode() && authenticatedIdPs.isEmpty()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing in Dumb mode");
        }
        try {
            request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
            response.sendRedirect(loginPage + ("?" + context.getContextIdIncludedQueryParams()) + "&authenticators=" + URLEncoder.encode(authenticatorNames, "UTF-8") + "&hrd=true");
        } catch (IOException e) {
            throw new FrameworkException(e.getMessage(), e);
        }
    } else {
        if (!(context.isForceAuthenticate() || stepConfig.isForced()) && !authenticatedStepIdps.isEmpty()) {
            Map.Entry<String, AuthenticatorConfig> entry = authenticatedStepIdps.entrySet().iterator().next();
            String idp = entry.getKey();
            AuthenticatorConfig authenticatorConfig = entry.getValue();
            if (context.isReAuthenticate()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Re-authenticating with " + idp + " IdP");
                }
                try {
                    context.setExternalIdP(ConfigurationFacade.getInstance().getIdPConfigByName(idp, context.getTenantDomain()));
                } catch (IdentityProviderManagementException e) {
                    LOG.error("Exception while getting IdP by name", e);
                }
                doAuthentication(request, response, context, authenticatorConfig);
                return;
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Already authenticated. Skipping the step");
                }
                // skip the step if this is a normal request
                AuthenticatedIdPData authenticatedIdPData = authenticatedIdPs.get(idp);
                populateStepConfigWithAuthenticationDetails(stepConfig, authenticatedIdPData, authenticatedStepIdps.get(idp));
                context.getCurrentAuthenticatedIdPs().put(idp, authenticatedIdPData);
                stepConfig.setCompleted(true);
                request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
                return;
            }
        } else {
            // Find if step contains only a single authenticator with a single
            // IdP. If yes, don't send to the multi-option page. Call directly.
            boolean sendToPage = false;
            boolean isAuthFlowHandlerOrBasicAuthInMultiOptionStep = false;
            AuthenticatorConfig authenticatorConfig = null;
            // Are there multiple authenticators?
            if (authConfigList.size() > 1) {
                sendToPage = true;
                // redirecting to the multi option page.
                for (AuthenticatorConfig config : authConfigList) {
                    if ((config.getApplicationAuthenticator() instanceof AuthenticationFlowHandler) || (config.getApplicationAuthenticator() instanceof LocalApplicationAuthenticator && (BASIC_AUTH_MECHANISM).equalsIgnoreCase(config.getApplicationAuthenticator().getAuthMechanism()))) {
                        authenticatorConfig = config;
                        isAuthFlowHandlerOrBasicAuthInMultiOptionStep = true;
                        sendToPage = false;
                        break;
                    }
                }
            } else {
                // Are there multiple IdPs in the single authenticator?
                authenticatorConfig = authConfigList.get(0);
                if (authenticatorConfig.getIdpNames().size() > 1) {
                    sendToPage = true;
                }
            }
            if (!sendToPage) {
                // call directly
                if (!authenticatorConfig.getIdpNames().isEmpty()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Step contains only a single IdP. Going to call it directly");
                    }
                    // set the IdP to be called in the context
                    try {
                        context.setExternalIdP(ConfigurationFacade.getInstance().getIdPConfigByName(authenticatorConfig.getIdpNames().get(0), context.getTenantDomain()));
                    } catch (IdentityProviderManagementException e) {
                        LOG.error("Exception while getting IdP by name", e);
                    }
                }
                doAuthentication(request, response, context, authenticatorConfig);
                /* If an authentication flow handler is redirected with incomplete status,
                    it will redirect to multi option page, as multi-option is available */
                if ((request.getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS)) == AuthenticatorFlowStatus.INCOMPLETE && isAuthFlowHandlerOrBasicAuthInMultiOptionStep) {
                    sendToMultiOptionPage(stepConfig, request, context, response, authenticatorNames);
                }
                return;
            } else {
                // else send to the multi option page.
                sendToMultiOptionPage(stepConfig, request, context, response, authenticatorNames);
                return;
            }
        }
    }
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) IOException(java.io.IOException) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator) AuthenticationFlowHandler(org.wso2.carbon.identity.application.authentication.framework.AuthenticationFlowHandler) Map(java.util.Map) HashMap(java.util.HashMap) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

Example 2 with AuthenticatedIdPData

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData in project carbon-identity-framework by wso2.

the class DefaultStepHandler method doAuthentication.

protected void doAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, AuthenticatorConfig authenticatorConfig) throws FrameworkException {
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    int currentStep = context.getCurrentStep();
    StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);
    ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
    if (authenticator == null) {
        LOG.error("Authenticator is null for AuthenticatorConfig: " + authenticatorConfig.getName());
        return;
    }
    String idpName = FrameworkConstants.LOCAL_IDP_NAME;
    if (context.getExternalIdP() != null && authenticator instanceof FederatedApplicationAuthenticator) {
        idpName = context.getExternalIdP().getIdPName();
    }
    try {
        context.setAuthenticatorProperties(FrameworkUtils.getAuthenticatorPropertyMapFromIdP(context.getExternalIdP(), authenticator.getName()));
        AuthenticatorFlowStatus status = authenticator.process(request, response, context);
        request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status);
        if (LOG.isDebugEnabled()) {
            LOG.debug(authenticator.getName() + " returned: " + status.toString());
        }
        if (status == AuthenticatorFlowStatus.INCOMPLETE) {
            context.setCurrentAuthenticator(authenticator.getName());
            if (LOG.isDebugEnabled()) {
                LOG.debug(authenticator.getName() + " is redirecting");
            }
            return;
        }
        if (authenticator instanceof FederatedApplicationAuthenticator) {
            if (context.getSubject().getUserName() == null) {
                // Set subject identifier as the default username for federated users
                String authenticatedSubjectIdentifier = context.getSubject().getAuthenticatedSubjectIdentifier();
                context.getSubject().setUserName(authenticatedSubjectIdentifier);
            }
            if (context.getSubject().getFederatedIdPName() == null && context.getExternalIdP() != null) {
                // Setting identity provider's name
                context.getSubject().setFederatedIdPName(idpName);
            }
            if (context.getSubject().getTenantDomain() == null) {
                // Setting service provider's tenant domain as the default tenant for federated users
                String tenantDomain = context.getTenantDomain();
                context.getSubject().setTenantDomain(tenantDomain);
            }
            try {
                // Check if the user id is available for the user. If the user id is not available or cannot be
                // resolved, UserIdNotFoundException is thrown.
                String userId = context.getSubject().getUserId();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("User id is available for user: " + userId);
                }
            } catch (UserIdNotFoundException e) {
                String tenantDomain = context.getSubject().getTenantDomain();
                int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
                String authenticatedSubjectIdentifier = context.getSubject().getAuthenticatedSubjectIdentifier();
                String federatedIdPName = context.getSubject().getFederatedIdPName();
                try {
                    int idpId = UserSessionStore.getInstance().getIdPId(federatedIdPName, tenantId);
                    String userId = UserSessionStore.getInstance().getFederatedUserId(authenticatedSubjectIdentifier, tenantId, idpId);
                    try {
                        if (userId == null) {
                            userId = UUID.randomUUID().toString();
                            UserSessionStore.getInstance().storeUserData(userId, authenticatedSubjectIdentifier, tenantId, idpId);
                        }
                    } catch (DuplicatedAuthUserException e1) {
                        String msg = "User authenticated is already persisted. Username: " + authenticatedSubjectIdentifier + " Tenant Domain:" + tenantDomain + " IdP: " + federatedIdPName;
                        LOG.warn(msg);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(msg, e1);
                        }
                        // Since duplicate entry was found, let's try to get the ID again.
                        userId = UserSessionStore.getInstance().getFederatedUserId(authenticatedSubjectIdentifier, tenantId, idpId);
                    }
                    context.getSubject().setUserId(userId);
                } catch (UserSessionException e2) {
                    LOG.error("Error while resolving the user id for federated user.", e2);
                }
            }
        }
        AuthenticatedIdPData authenticatedIdPData = getAuthenticatedIdPData(context, idpName);
        // store authenticated user
        AuthenticatedUser authenticatedUser = context.getSubject();
        stepConfig.setAuthenticatedUser(authenticatedUser);
        authenticatedIdPData.setUser(authenticatedUser);
        authenticatorConfig.setAuthenticatorStateInfo(context.getStateInfo());
        stepConfig.setAuthenticatedAutenticator(authenticatorConfig);
        // store authenticated idp
        stepConfig.setAuthenticatedIdP(idpName);
        authenticatedIdPData.setIdpName(idpName);
        authenticatedIdPData.addAuthenticator(authenticatorConfig);
        // add authenticated idp data to the session wise map
        context.getCurrentAuthenticatedIdPs().put(idpName, authenticatedIdPData);
        // Add SAML federated idp session index into the authentication step history.
        String idpSessionIndex = null;
        String parameterName = FEDERATED_IDP_SESSION_ID + idpName;
        AuthHistory authHistory = new AuthHistory(authenticator.getName(), idpName);
        if (context.getParameters() != null && context.getParameters().containsKey(parameterName)) {
            Object idpSessionIndexParamValue = context.getParameter(parameterName);
            if (idpSessionIndexParamValue != null) {
                idpSessionIndex = idpSessionIndexParamValue.toString();
            }
        }
        if (StringUtils.isNotBlank(context.getCurrentAuthenticator()) && StringUtils.isNotBlank(idpSessionIndex)) {
            authHistory.setIdpSessionIndex(idpSessionIndex);
            authHistory.setRequestType(context.getRequestType());
        }
        Serializable startTime = context.getAnalyticsData(FrameworkConstants.AnalyticsData.CURRENT_AUTHENTICATOR_START_TIME);
        if (startTime instanceof Long) {
            authHistory.setDuration((long) startTime - System.currentTimeMillis());
        }
        authHistory.setSuccess(true);
        context.addAuthenticationStepHistory(authHistory);
        String initiator = null;
        if (stepConfig.getAuthenticatedUser() != null) {
            initiator = stepConfig.getAuthenticatedUser().toFullQualifiedUsername();
        }
        String data = "Step: " + stepConfig.getOrder() + ", IDP: " + stepConfig.getAuthenticatedIdP() + ", Authenticator:" + stepConfig.getAuthenticatedAutenticator().getName();
        if (!isLegacyAuditLogsDisabled()) {
            audit.info(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, SUCCESS));
        }
    } catch (InvalidCredentialsException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("A login attempt was failed due to invalid credentials", e);
        }
        String data = "Step: " + stepConfig.getOrder() + ", IDP: " + idpName + ", Authenticator:" + authenticatorConfig.getName();
        String initiator = null;
        if (e.getUser() != null) {
            initiator = e.getUser().toFullQualifiedUsername();
        } else if (context.getSubject() != null) {
            initiator = context.getSubject().toFullQualifiedUsername();
        }
        if (!isLegacyAuditLogsDisabled()) {
            audit.warn(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, FAILURE));
        }
        handleFailedAuthentication(request, response, context, authenticatorConfig, e.getUser());
    } catch (AuthenticationFailedException e) {
        IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg();
        if (errorContext != null) {
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (!IdentityCoreConstants.ADMIN_FORCED_USER_PASSWORD_RESET_VIA_OTP_ERROR_CODE.equals(errorContext.getErrorCode()) && !(rootCause instanceof UserStoreClientException) && !IdentityCoreConstants.USER_ACCOUNT_LOCKED_ERROR_CODE.equals(errorContext.getErrorCode()) && !IdentityCoreConstants.USER_ACCOUNT_DISABLED_ERROR_CODE.equals(errorContext.getErrorCode()) && !IdentityCoreConstants.USER_ACCOUNT_NOT_CONFIRMED_ERROR_CODE.equals(errorContext.getErrorCode())) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Authentication failed exception!", e);
                }
                LOG.error("Authentication failed exception! " + e.getMessage());
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Authentication failed exception!", e);
                }
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authentication failed exception!", e);
            }
            LOG.error("Authentication failed exception! " + e.getMessage());
        }
        String data = "Step: " + stepConfig.getOrder() + ", IDP: " + idpName + ", Authenticator:" + authenticatorConfig.getName();
        String initiator = null;
        if (e.getUser() != null) {
            initiator = e.getUser().toFullQualifiedUsername();
        } else if (context.getSubject() != null) {
            initiator = context.getSubject().toFullQualifiedUsername();
        }
        if (!isLegacyAuditLogsDisabled()) {
            audit.warn(String.format(AUDIT_MESSAGE, initiator, "Authenticate", "ApplicationAuthenticationFramework", data, FAILURE));
        }
        handleFailedAuthentication(request, response, context, authenticatorConfig, e.getUser());
    } catch (LogoutFailedException e) {
        throw new FrameworkException(e.getMessage(), e);
    }
    stepConfig.setCompleted(true);
}
Also used : Serializable(java.io.Serializable) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) DuplicatedAuthUserException(org.wso2.carbon.identity.application.authentication.framework.exception.DuplicatedAuthUserException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) LogoutFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityErrorMsgContext(org.wso2.carbon.identity.core.model.IdentityErrorMsgContext) FederatedApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.FederatedApplicationAuthenticator) LocalApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) InvalidCredentialsException(org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

Example 3 with AuthenticatedIdPData

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData in project carbon-identity-framework by wso2.

the class DefaultAuthenticationRequestHandler method setAuthenticatedIDPsOfApp.

private void setAuthenticatedIDPsOfApp(SessionContext sessionContext, Map<String, AuthenticatedIdPData> authenticatedIdPs, String applicationName) throws FrameworkException {
    if (log.isDebugEnabled()) {
        log.debug("Getting current authenticatedIDPs of the application from authentication context and setting " + "it into session context for application: " + applicationName);
    }
    Map<String, AuthenticatedIdPData> authenticatedIdPDataMap = new HashMap<>();
    for (Map.Entry<String, AuthenticatedIdPData> entry : authenticatedIdPs.entrySet()) {
        try {
            AuthenticatedIdPData authenticatedIdpData = (AuthenticatedIdPData) entry.getValue().clone();
            authenticatedIdPDataMap.put(authenticatedIdpData.getIdpName(), authenticatedIdpData);
        } catch (CloneNotSupportedException e) {
            String errorMsg = "Error while cloning AuthenticatedIdPData object.";
            throw new FrameworkException(errorMsg, e);
        }
    }
    sessionContext.setAuthenticatedIdPsOfApp(applicationName, authenticatedIdPDataMap);
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

Example 4 with AuthenticatedIdPData

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData in project carbon-identity-framework by wso2.

the class DefaultAuthenticationRequestHandler method storeSessionData.

/**
 * Method used to store user and session related data to the database.
 *
 * @param context           {@link AuthenticationContext} object with the authentication request related data
 * @param sessionContextKey of the authenticated session
 */
private void storeSessionData(AuthenticationContext context, String sessionContextKey) throws UserSessionException {
    String subject = context.getSequenceConfig().getAuthenticatedUser().getAuthenticatedSubjectIdentifier();
    String inboundAuth = context.getCallerPath().substring(1);
    int appId = context.getSequenceConfig().getApplicationConfig().getApplicationID();
    for (AuthenticatedIdPData authenticatedIdPData : context.getCurrentAuthenticatedIdPs().values()) {
        AuthenticatedUser user = authenticatedIdPData.getUser();
        try {
            String userId = user.getUserId();
            try {
                if (!UserSessionStore.getInstance().isExistingMapping(userId, sessionContextKey)) {
                    UserSessionStore.getInstance().storeUserSessionData(userId, sessionContextKey);
                }
                /*
                For JIT provisioned users, if AssertIdentity Using Mapped Local Subject Identifier config is enabled in
                the app level, add an entry in the IDN_AUTH_USER_SESSION_MAPPING table with local userId.
                 */
                if (user.isFederatedUser() && context.getSequenceConfig().getApplicationConfig().isMappedSubjectIDSelected()) {
                    String localUserId = FrameworkUtils.resolveUserIdFromUsername(IdentityTenantUtil.getTenantId(user.getTenantDomain()), user.getUserStoreDomain(), user.getUserName());
                    if (StringUtils.isNotEmpty(localUserId) && !UserSessionStore.getInstance().isExistingMapping(localUserId, sessionContextKey)) {
                        UserSessionStore.getInstance().storeUserSessionData(localUserId, sessionContextKey);
                    }
                }
            } catch (UserSessionException e) {
                throw new UserSessionException("Error while storing session data for user: " + user.getLoggableUserId(), e);
            }
        } catch (UserIdNotFoundException e) {
            // the mapping is not stored.
            if (log.isDebugEnabled()) {
                log.debug("A unique user id is not set for the user: " + user.getLoggableUserId() + ". Hence the session information of the user is not stored.");
            }
        }
    }
    if (appId > 0) {
        storeAppSessionData(sessionContextKey, subject, appId, inboundAuth);
    }
}
Also used : UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) AuthenticatedIdPData(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)

Example 5 with AuthenticatedIdPData

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData in project carbon-identity-framework by wso2.

the class DefaultRequestPathBasedSequenceHandler method handlePostAuthentication.

protected void handlePostAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context, AuthenticatedIdPData authenticatedIdPData) throws FrameworkException {
    if (log.isDebugEnabled()) {
        log.debug("Handling Post Authentication tasks");
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    Map<String, String> mappedAttrs;
    StringBuilder jsonBuilder = new StringBuilder();
    // build the authenticated idps JWT to send to the calling servlet.
    jsonBuilder.append("\"idps\":");
    jsonBuilder.append("[");
    // build the JSON object for this step
    jsonBuilder.append("{");
    jsonBuilder.append("\"idp\":\"").append(authenticatedIdPData.getIdpName()).append("\",");
    jsonBuilder.append("\"authenticator\":\"").append(authenticatedIdPData.getAuthenticator().getApplicationAuthenticator().getName()).append("\"");
    // wrap up the JSON object
    jsonBuilder.append("}");
    jsonBuilder.append("]");
    sequenceConfig.setAuthenticatedIdPs(IdentityApplicationManagementUtil.getSignedJWT(jsonBuilder.toString(), sequenceConfig.getApplicationConfig().getServiceProvider()));
    mappedAttrs = handleClaimMappings(context);
    String spRoleUri = getSpRoleClaimUri(sequenceConfig.getApplicationConfig());
    String roleAttr = mappedAttrs.get(spRoleUri);
    if (StringUtils.isNotBlank(roleAttr)) {
        String[] roles = roleAttr.split(Pattern.quote(FrameworkUtils.getMultiAttributeSeparator()));
        mappedAttrs.put(spRoleUri, getServiceProviderMappedUserRoles(sequenceConfig, Arrays.asList(roles)));
    }
    sequenceConfig.getAuthenticatedUser().setUserAttributes(FrameworkUtils.buildClaimMappings(mappedAttrs));
    if (StringUtils.isNotBlank(context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri())) {
        Map<String, String> unfilteredClaimValues = (Map<String, String>) context.getProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES);
        String subjectClaimUri = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri().trim();
        String subjectClaimValue;
        if (unfilteredClaimValues != null) {
            subjectClaimValue = unfilteredClaimValues.get(subjectClaimUri);
        } else {
            subjectClaimValue = mappedAttrs.get(subjectClaimUri);
        }
        if (subjectClaimValue != null) {
            AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser();
            authenticatedUser.setAuthenticatedSubjectIdentifier(subjectClaimValue);
            if (log.isDebugEnabled()) {
                log.debug("Authenticated User: " + sequenceConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
                log.debug("Authenticated User Tenant Domain: " + sequenceConfig.getAuthenticatedUser().getTenantDomain());
            }
        }
    }
}
Also used : SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) Map(java.util.Map) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

AuthenticatedIdPData (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedIdPData)12 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)7 AuthenticatorConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig)6 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)5 HashMap (java.util.HashMap)4 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)4 Map (java.util.Map)3 ApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator)3 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)3 IOException (java.io.IOException)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 Test (org.testng.annotations.Test)2 AuthenticatorFlowStatus (org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus)2 LocalApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator)2 ApplicationConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig)2 AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)2 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)2 InvalidCredentialsException (org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException)2 LogoutFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException)2