Search in sources :

Example 1 with AuthHistory

use of org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory in project carbon-identity-framework by wso2.

the class UserSessionStore method storeFederatedAuthSessionInfo.

/**
 * Store session details of a given session context key to map the session context key with
 * the federated IdP's session ID.
 *
 * @param sessionContextKey Session Context Key.
 * @param authHistory       History of the authentication flow.
 * @throws UserSessionException Error while storing session details.
 */
public void storeFederatedAuthSessionInfo(String sessionContextKey, AuthHistory authHistory) throws UserSessionException {
    try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) {
        try (PreparedStatement prepStmt = connection.prepareStatement(SQLQueries.SQL_STORE_FEDERATED_AUTH_SESSION_INFO)) {
            prepStmt.setString(1, authHistory.getIdpSessionIndex());
            prepStmt.setString(2, sessionContextKey);
            prepStmt.setString(3, authHistory.getIdpName());
            prepStmt.setString(4, authHistory.getAuthenticatorName());
            prepStmt.setString(5, authHistory.getRequestType());
            prepStmt.execute();
        } catch (SQLException e1) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            throw new UserSessionException("Error while adding session details of the session index:" + sessionContextKey + ", IdP:" + authHistory.getIdpName(), e1);
        }
    } catch (SQLException e) {
        throw new UserSessionException("Error while adding session details of the session index:" + sessionContextKey + ", IdP:" + authHistory.getIdpName(), e);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException)

Example 2 with AuthHistory

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

use of org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory in project carbon-identity-framework by wso2.

the class DefaultAuthenticationRequestHandler method concludeFlow.

/**
 * Sends the response to the servlet that initiated the authentication flow
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void concludeFlow(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
    if (log.isDebugEnabled()) {
        log.debug("Concluding the Authentication Flow");
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    sequenceConfig.setCompleted(false);
    AuthenticationResult authenticationResult = new AuthenticationResult();
    boolean isAuthenticated = context.isRequestAuthenticated();
    authenticationResult.setAuthenticated(isAuthenticated);
    String authenticatedUserTenantDomain = getAuthenticatedUserTenantDomain(context, authenticationResult);
    authenticationResult.setSaaSApp(sequenceConfig.getApplicationConfig().isSaaSApp());
    if (isAuthenticated) {
        if (!sequenceConfig.getApplicationConfig().isSaaSApp()) {
            String spTenantDomain = context.getTenantDomain();
            String userTenantDomain = sequenceConfig.getAuthenticatedUser().getTenantDomain();
            if (StringUtils.isNotEmpty(userTenantDomain)) {
                if (StringUtils.isNotEmpty(spTenantDomain) && !spTenantDomain.equals(userTenantDomain)) {
                    throw new FrameworkException("Service Provider tenant domain must be equal to user tenant " + "domain for non-SaaS applications");
                }
            }
        }
        authenticationResult.setSubject(new AuthenticatedUser(sequenceConfig.getAuthenticatedUser()));
        ApplicationConfig appConfig = sequenceConfig.getApplicationConfig();
        if (appConfig.getServiceProvider().getLocalAndOutBoundAuthenticationConfig().isAlwaysSendBackAuthenticatedListOfIdPs()) {
            authenticationResult.setAuthenticatedIdPs(sequenceConfig.getAuthenticatedIdPs());
        }
        // SessionContext is retained across different SP requests in the same browser session.
        // it is tracked by a cookie
        SessionContext sessionContext = null;
        String commonAuthCookie = null;
        String sessionContextKey = null;
        String analyticsSessionAction = null;
        // When getting the cookie, it will not give the path. When paths are tenant qualified, it will only give
        // the cookies matching that path.
        Cookie authCookie = FrameworkUtils.getAuthCookie(request);
        // Force authentication requires the creation of a new session. Therefore skip using the existing session
        if (authCookie != null && !context.isForceAuthenticate()) {
            commonAuthCookie = authCookie.getValue();
            if (commonAuthCookie != null) {
                sessionContextKey = DigestUtils.sha256Hex(commonAuthCookie);
                sessionContext = FrameworkUtils.getSessionContextFromCache(sessionContextKey, context.getLoginTenantDomain());
            }
        }
        String applicationTenantDomain = getApplicationTenantDomain(context);
        // session context may be null when cache expires therefore creating new cookie as well.
        if (sessionContext != null) {
            analyticsSessionAction = FrameworkConstants.AnalyticsAttributes.SESSION_UPDATE;
            sessionContext.getAuthenticatedSequences().put(appConfig.getApplicationName(), sequenceConfig);
            sessionContext.getAuthenticatedIdPs().putAll(context.getCurrentAuthenticatedIdPs());
            if (!context.isPassiveAuthenticate()) {
                setAuthenticatedIDPsOfApp(sessionContext, context.getCurrentAuthenticatedIdPs(), appConfig.getApplicationName());
            }
            sessionContext.getSessionAuthHistory().resetHistory(AuthHistory.merge(sessionContext.getSessionAuthHistory().getHistory(), context.getAuthenticationStepHistory()));
            populateAuthenticationContextHistory(authenticationResult, context, sessionContext);
            long updatedSessionTime = System.currentTimeMillis();
            if (!context.isPreviousAuthTime()) {
                sessionContext.addProperty(FrameworkConstants.UPDATED_TIMESTAMP, updatedSessionTime);
            }
            authenticationResult.addProperty(FrameworkConstants.AnalyticsAttributes.SESSION_ID, sessionContextKey);
            List<AuthenticationContextProperty> authenticationContextProperties = new ArrayList<>();
            // Authentication context properties from already authenticated IdPs
            if (sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) != null) {
                List<AuthenticationContextProperty> existingAuthenticationContextProperties = (List<AuthenticationContextProperty>) sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES);
                for (AuthenticationContextProperty contextProperty : existingAuthenticationContextProperties) {
                    for (StepConfig stepConfig : context.getSequenceConfig().getStepMap().values()) {
                        if (stepConfig.getAuthenticatedIdP().equals(contextProperty.getIdPName())) {
                            authenticationContextProperties.add(contextProperty);
                            break;
                        }
                    }
                }
            }
            Long createdTime = (Long) sessionContext.getProperty(FrameworkConstants.CREATED_TIMESTAMP);
            if (createdTime != null) {
                authenticationResult.addProperty(FrameworkConstants.CREATED_TIMESTAMP, createdTime);
            }
            // Authentication context properties received from newly authenticated IdPs
            if (context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) != null) {
                authenticationContextProperties.addAll((List<AuthenticationContextProperty>) context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
                if (sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) == null) {
                    sessionContext.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, authenticationContextProperties);
                } else {
                    List<AuthenticationContextProperty> existingAuthenticationContextProperties = (List<AuthenticationContextProperty>) sessionContext.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES);
                    existingAuthenticationContextProperties.addAll((List<AuthenticationContextProperty>) context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
                }
            }
            if (!authenticationContextProperties.isEmpty()) {
                if (log.isDebugEnabled()) {
                    log.debug("AuthenticationContextProperties are available.");
                }
                authenticationResult.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, authenticationContextProperties);
            }
            FrameworkUtils.updateSessionLastAccessTimeMetadata(sessionContextKey, updatedSessionTime);
            /*
                 * In the default configuration, the expiry time of the commonAuthCookie is fixed when rememberMe
                 * option is selected. With this config, the expiry time will increase at every authentication.
                 */
            if (sessionContext.isRememberMe() && Boolean.parseBoolean(IdentityUtil.getProperty(IdentityConstants.ServerConfig.EXTEND_REMEMBER_ME_SESSION_ON_AUTH))) {
                context.setRememberMe(sessionContext.isRememberMe());
                setAuthCookie(request, response, context, commonAuthCookie, applicationTenantDomain);
            }
            if (context.getRuntimeClaims().size() > 0) {
                sessionContext.addProperty(FrameworkConstants.RUNTIME_CLAIMS, context.getRuntimeClaims());
            }
            handleSessionContextUpdate(context.getRequestType(), sessionContextKey, sessionContext, request, response, context);
            // TODO add to cache?
            // store again. when replicate  cache is used. this may be needed.
            FrameworkUtils.addSessionContextToCache(sessionContextKey, sessionContext, applicationTenantDomain, context.getLoginTenantDomain());
        } else {
            analyticsSessionAction = FrameworkConstants.AnalyticsAttributes.SESSION_CREATE;
            sessionContext = new SessionContext();
            // To identify first login
            context.setProperty(FrameworkConstants.AnalyticsAttributes.IS_INITIAL_LOGIN, true);
            sessionContext.getAuthenticatedSequences().put(appConfig.getApplicationName(), sequenceConfig);
            sessionContext.setAuthenticatedIdPs(context.getCurrentAuthenticatedIdPs());
            setAuthenticatedIDPsOfApp(sessionContext, context.getCurrentAuthenticatedIdPs(), appConfig.getApplicationName());
            sessionContext.setRememberMe(context.isRememberMe());
            if (context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES) != null) {
                if (log.isDebugEnabled()) {
                    log.debug("AuthenticationContextProperties are available.");
                }
                authenticationResult.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
                // Add to session context
                sessionContext.addProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES, context.getProperty(FrameworkConstants.AUTHENTICATION_CONTEXT_PROPERTIES));
            }
            String sessionKey = UUIDGenerator.generateUUID();
            sessionContextKey = DigestUtils.sha256Hex(sessionKey);
            sessionContext.addProperty(FrameworkConstants.AUTHENTICATED_USER, authenticationResult.getSubject());
            sessionContext.addProperty(FrameworkUtils.TENANT_DOMAIN, context.getLoginTenantDomain());
            Long createdTimeMillis = System.currentTimeMillis();
            sessionContext.addProperty(FrameworkConstants.CREATED_TIMESTAMP, createdTimeMillis);
            authenticationResult.addProperty(FrameworkConstants.CREATED_TIMESTAMP, createdTimeMillis);
            authenticationResult.addProperty(FrameworkConstants.AnalyticsAttributes.SESSION_ID, sessionContextKey);
            sessionContext.getSessionAuthHistory().resetHistory(AuthHistory.merge(sessionContext.getSessionAuthHistory().getHistory(), context.getAuthenticationStepHistory()));
            populateAuthenticationContextHistory(authenticationResult, context, sessionContext);
            if (context.getRuntimeClaims().size() > 0) {
                sessionContext.addProperty(FrameworkConstants.RUNTIME_CLAIMS, context.getRuntimeClaims());
            }
            handleInboundSessionCreate(context.getRequestType(), sessionContextKey, sessionContext, request, response, context);
            FrameworkUtils.addSessionContextToCache(sessionContextKey, sessionContext, applicationTenantDomain, context.getLoginTenantDomain());
            setAuthCookie(request, response, context, sessionKey, applicationTenantDomain);
            if (FrameworkServiceDataHolder.getInstance().isUserSessionMappingEnabled()) {
                try {
                    storeSessionMetaData(sessionContextKey, request);
                } catch (UserSessionException e) {
                    log.error("Storing session meta data failed.", e);
                }
            }
        }
        if (authenticatedUserTenantDomain == null) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        }
        if (FrameworkServiceDataHolder.getInstance().isUserSessionMappingEnabled()) {
            try {
                storeSessionData(context, sessionContextKey);
            } catch (UserSessionException e) {
                throw new FrameworkException("Error while storing session details of the authenticated user to " + "the database", e);
            }
        }
        // store the saml index with the session context key for the single logout.
        if (context.getAuthenticationStepHistory() != null) {
            UserSessionStore userSessionStore = UserSessionStore.getInstance();
            for (AuthHistory authHistory : context.getAuthenticationStepHistory()) {
                if (StringUtils.isNotBlank(authHistory.getIdpSessionIndex()) && StringUtils.isNotBlank(authHistory.getIdpName())) {
                    try {
                        if (!userSessionStore.hasExistingFederatedAuthSession(authHistory.getIdpSessionIndex())) {
                            userSessionStore.storeFederatedAuthSessionInfo(sessionContextKey, authHistory);
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug(String.format("Federated auth session with the id: %s already exists", authHistory.getIdpSessionIndex()));
                            }
                            userSessionStore.updateFederatedAuthSessionInfo(sessionContextKey, authHistory);
                        }
                    } catch (UserSessionException e) {
                        throw new FrameworkException("Error while storing federated authentication session details " + "of the authenticated user to the database", e);
                    }
                }
            }
        }
        FrameworkUtils.publishSessionEvent(sessionContextKey, request, context, sessionContext, sequenceConfig.getAuthenticatedUser(), analyticsSessionAction);
        publishAuthenticationSuccess(request, context, sequenceConfig.getAuthenticatedUser());
    }
    // authenticator in multi steps scenario. Ex. Fido
    if (FrameworkUtils.getCacheDisabledAuthenticators().contains(context.getRequestType()) && (response instanceof CommonAuthResponseWrapper) && !((CommonAuthResponseWrapper) response).isWrappedByFramework()) {
        // Set the result as request attribute
        request.setAttribute("sessionDataKey", context.getCallerSessionKey());
        addAuthenticationResultToRequest(request, authenticationResult);
    } else {
        FrameworkUtils.addAuthenticationResultToCache(context.getCallerSessionKey(), authenticationResult);
    }
    /*
         * TODO Cache retaining is a temporary fix. Remove after Google fixes
         * http://code.google.com/p/gdata-issues/issues/detail?id=6628
         */
    String retainCache = System.getProperty("retainCache");
    if (retainCache == null) {
        FrameworkUtils.removeAuthenticationContextFromCache(context.getContextIdentifier());
    }
    sendResponse(request, response, context);
}
Also used : SessionNonceCookieUtil.removeNonceCookie(org.wso2.carbon.identity.application.authentication.framework.util.SessionNonceCookieUtil.removeNonceCookie) SessionNonceCookieUtil.addNonceCookie(org.wso2.carbon.identity.application.authentication.framework.util.SessionNonceCookieUtil.addNonceCookie) SessionNonceCookieUtil.validateNonceCookie(org.wso2.carbon.identity.application.authentication.framework.util.SessionNonceCookieUtil.validateNonceCookie) Cookie(javax.servlet.http.Cookie) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) UserSessionStore(org.wso2.carbon.identity.application.authentication.framework.store.UserSessionStore) ArrayList(java.util.ArrayList) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) ApplicationConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ApplicationConfig) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) List(java.util.List) ArrayList(java.util.ArrayList) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) AuthenticationContextProperty(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationContextProperty) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 4 with AuthHistory

use of org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory in project carbon-identity-framework by wso2.

the class DefaultLogoutRequestHandler method handle.

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
    if (log.isTraceEnabled()) {
        log.trace("Inside handle()");
    }
    SequenceConfig sequenceConfig = context.getSequenceConfig();
    // Retrieve session information from cache.
    SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(context.getSessionIdentifier(), context.getLoginTenantDomain());
    ExternalIdPConfig externalIdPConfig = null;
    // Remove the session related information from the session tables.
    clearUserSessionData(request);
    if (FrameworkServiceDataHolder.getInstance().getAuthnDataPublisherProxy() != null && FrameworkServiceDataHolder.getInstance().getAuthnDataPublisherProxy().isEnabled(context) && sessionContext != null) {
        Object authenticatedUserObj = sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
        AuthenticatedUser authenticatedUser = new AuthenticatedUser();
        if (authenticatedUserObj instanceof AuthenticatedUser) {
            authenticatedUser = (AuthenticatedUser) authenticatedUserObj;
        }
        FrameworkUtils.publishSessionEvent(context.getSessionIdentifier(), request, context, sessionContext, authenticatedUser, FrameworkConstants.AnalyticsAttributes.SESSION_TERMINATE);
    }
    // Remove federated authentication session details from the database.
    if (sessionContext != null && StringUtils.isNotBlank(context.getSessionIdentifier()) && sessionContext.getSessionAuthHistory() != null && sessionContext.getSessionAuthHistory().getHistory() != null) {
        for (AuthHistory authHistory : sessionContext.getSessionAuthHistory().getHistory()) {
            if (FED_AUTH_NAME.equals(authHistory.getAuthenticatorName())) {
                try {
                    UserSessionStore.getInstance().removeFederatedAuthSessionInfo(context.getSessionIdentifier());
                    break;
                } catch (UserSessionException e) {
                    throw new FrameworkException("Error while deleting federated authentication session details for" + " the session context key :" + context.getSessionIdentifier(), e);
                }
            }
        }
    }
    // remove SessionContext from the cache and auth cookie before sending logout request to federated IDP,
    // without waiting till a logout response is received from federated IDP.
    // remove the SessionContext from the cache
    FrameworkUtils.removeSessionContextFromCache(context.getSessionIdentifier(), context.getLoginTenantDomain());
    // remove the cookie
    if (IdentityTenantUtil.isTenantedSessionsEnabled()) {
        FrameworkUtils.removeAuthCookie(request, response, context.getLoginTenantDomain());
    } else {
        FrameworkUtils.removeAuthCookie(request, response);
    }
    if (context.isPreviousSessionFound()) {
        // if this is the start of the logout sequence
        if (context.getCurrentStep() == 0) {
            context.setCurrentStep(1);
        }
        int stepCount = sequenceConfig.getStepMap().size();
        while (context.getCurrentStep() <= stepCount) {
            int currentStep = context.getCurrentStep();
            StepConfig stepConfig = sequenceConfig.getStepMap().get(currentStep);
            AuthenticatorConfig authenticatorConfig = stepConfig.getAuthenticatedAutenticator();
            if (authenticatorConfig == null) {
                authenticatorConfig = sequenceConfig.getAuthenticatedReqPathAuthenticator();
            }
            ApplicationAuthenticator authenticator = authenticatorConfig.getApplicationAuthenticator();
            String idpName = stepConfig.getAuthenticatedIdP();
            // TODO: Need to fix occurrences where idPName becomes "null"
            if ((idpName == null || "null".equalsIgnoreCase(idpName) || idpName.isEmpty()) && sequenceConfig.getAuthenticatedReqPathAuthenticator() != null) {
                idpName = FrameworkConstants.LOCAL_IDP_NAME;
            }
            try {
                externalIdPConfig = ConfigurationFacade.getInstance().getIdPConfigByName(idpName, context.getTenantDomain());
                context.setExternalIdP(externalIdPConfig);
                context.setAuthenticatorProperties(FrameworkUtils.getAuthenticatorPropertyMapFromIdP(externalIdPConfig, authenticator.getName()));
                if (authenticatorConfig.getAuthenticatorStateInfo() != null) {
                    context.setStateInfo(authenticatorConfig.getAuthenticatorStateInfo());
                } else {
                    context.setStateInfo(getStateInfoFromPreviousAuthenticatedIdPs(idpName, authenticatorConfig.getName(), context));
                }
                AuthenticatorFlowStatus status = authenticator.process(request, response, context);
                request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, status);
                if (!status.equals(AuthenticatorFlowStatus.INCOMPLETE)) {
                    // TODO what if logout fails. this is an edge case
                    currentStep++;
                    context.setCurrentStep(currentStep);
                    continue;
                }
                // sends the logout request to the external IdP
                return;
            } catch (AuthenticationFailedException | LogoutFailedException e) {
                throw new FrameworkException("Exception while handling logout request", e);
            } catch (IdentityProviderManagementException e) {
                log.error("Exception while getting IdP by name", e);
            }
        }
    }
    try {
        sendResponse(request, response, context, true);
    } catch (ServletException | IOException e) {
        throw new FrameworkException(e.getMessage(), e);
    }
}
Also used : AuthenticatorConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) StepConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig) LogoutFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException) IOException(java.io.IOException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) ServletException(javax.servlet.ServletException) ApplicationAuthenticator(org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) SequenceConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig) ExternalIdPConfig(org.wso2.carbon.identity.application.authentication.framework.config.model.ExternalIdPConfig) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 5 with AuthHistory

use of org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory in project carbon-identity-framework by wso2.

the class GraphBasedSequenceHandlerCustomFunctionsTest method testHandleDynamicBoolean.

public void testHandleDynamicBoolean() throws Exception {
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
    JsFunctionRegistry jsFunctionRegistrar = new JsFunctionRegistryImpl();
    FrameworkServiceDataHolder.getInstance().setJsFunctionRegistry(jsFunctionRegistrar);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "fn1", (Function<JsAuthenticationContext, String>) GraphBasedSequenceHandlerCustomFunctionsTest::customFunction1);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getTrueFunction", (Function<JsAuthenticationContext, Boolean>) GraphBasedSequenceHandlerCustomFunctionsTest::customBoolean);
    jsFunctionRegistrar.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getTrueFunction2", (BiFunction<JsAuthenticationContext, String, Boolean>) GraphBasedSequenceHandlerCustomFunctionsTest::customBoolean2);
    ServiceProvider sp1 = getTestServiceProvider("js-sp-dynamic-1.xml");
    String script = "var onLoginRequest = function(context) {\n" + "    var myBool = getTrueFunction2(context, 'a');\n" + "    Log.info(\"My Bool Value \"+myBool);\n" + "    if(myBool) {\n" + "        Log.info(\"My Bool Is Selected \"+myBool);\n" + "        executeStep(1, {\n" + "            onSuccess : function(context) {\n" + "                executeStep(3);\n" + "            }\n" + "        });\n" + "        executeStep(2);\n" + "    }  else {\n" + "        Log.info(\"My Bool Not Selected \"+myBool);\n" + "        executeStep(1);\n" + "        executeStep(3);\n" + "    }\n" + "};";
    sp1.getLocalAndOutBoundAuthenticationConfig().getAuthenticationScriptConfig().setContent(script);
    AuthenticationContext context = processAndGetAuthenticationContext(new String[0], sp1);
    List<AuthHistory> authHistories = context.getAuthenticationStepHistory();
    assertNotNull(authHistories);
    assertEquals(authHistories.size(), 3);
    assertEquals(authHistories.get(0).getAuthenticatorName(), "BasicMockAuthenticator");
    assertEquals(authHistories.get(1).getAuthenticatorName(), "FptMockAuthenticator");
    assertEquals(authHistories.get(2).getAuthenticatorName(), "HwkMockAuthenticator");
}
Also used : JsFunctionRegistry(org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry) JsAuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext) AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) JsAuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext) JsFunctionRegistryImpl(org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsFunctionRegistryImpl) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)

Aggregations

AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)16 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)11 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)11 Test (org.testng.annotations.Test)10 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 JsFunctionRegistryImpl (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsFunctionRegistryImpl)5 JsAuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext)5 UserSessionException (org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException)5 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)4 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4 ApplicationAuthenticator (org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator)3 AuthenticatorFlowStatus (org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus)3 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)3 SessionContext (org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)3 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)3 LogoutFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException)3 ArrayList (java.util.ArrayList)2 JsFunctionRegistry (org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry)2