Search in sources :

Example 6 with UserSessionException

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

the class UserSessionStore method updateSessionMetaData.

/**
 * Update session meta data.
 *
 * @param sessionId    id of the authenticated session
 * @param propertyType type of the meta data
 * @param value        value of the meta data
 * @throws UserSessionException if the meta data update in the database fails.
 */
public void updateSessionMetaData(String sessionId, String propertyType, String value) throws UserSessionException {
    JdbcTemplate jdbcTemplate = JdbcUtils.getNewTemplate(JdbcUtils.Database.SESSION);
    try {
        String sqlStmt = isH2DB() ? SQLQueries.SQL_UPDATE_SESSION_META_DATA_H2 : SQLQueries.SQL_UPDATE_SESSION_META_DATA;
        jdbcTemplate.executeUpdate(sqlStmt, preparedStatement -> {
            preparedStatement.setString(1, value);
            preparedStatement.setString(2, sessionId);
            preparedStatement.setString(3, propertyType);
        });
    } catch (DataAccessException e) {
        throw new UserSessionException("Error while updating " + propertyType + " of session:" + sessionId + " in table " + IDN_AUTH_SESSION_META_DATA_TABLE + ".", e);
    }
}
Also used : JdbcTemplate(org.wso2.carbon.database.utils.jdbc.JdbcTemplate) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) DataAccessException(org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException)

Example 7 with UserSessionException

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

the class UserSessionStore method removeFederatedAuthSessionInfo.

/**
 * Remove federated authentication session details of a given session context key.
 *
 * @param sessionContextKey Session Context Key.
 * @throws UserSessionException Error while deleting session details of a given session id.
 */
public void removeFederatedAuthSessionInfo(String sessionContextKey) throws UserSessionException {
    try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) {
        try (PreparedStatement prepStmt = connection.prepareStatement(SQLQueries.SQL_DELETE_FEDERATED_AUTH_SESSION_INFO)) {
            prepStmt.setString(1, sessionContextKey);
            prepStmt.execute();
        } catch (SQLException e1) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
            throw new UserSessionException("Error while removing federated authentication session details of " + "the session index:" + sessionContextKey, e1);
        }
    } catch (SQLException e) {
        throw new UserSessionException("Error while removing federated authentication session details of " + "the session index:" + sessionContextKey, 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 8 with UserSessionException

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

the class UserSessionStore method getActiveSessionCount.

/**
 * Counts the number of active sessions of the given tenant domain. For a session to be active, the last access
 * time of the session should not be earlier than the session timeout time.
 *
 * @param tenantDomain tenant domain
 * @return number of active sessions of the given tenant domain
 * @throws UserSessionException if something goes wrong
 */
public int getActiveSessionCount(String tenantDomain) throws UserSessionException {
    int activeSessionCount = 0;
    int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
    long idleSessionTimeOut = TimeUnit.SECONDS.toMillis(IdPManagementUtil.getIdleSessionTimeOut(tenantDomain));
    long currentTime = System.currentTimeMillis();
    long minTimestamp = currentTime - idleSessionTimeOut;
    try (Connection connection = IdentityDatabaseUtil.getSessionDBConnection(false)) {
        String sqlStmt = isH2DB() ? SQLQueries.SQL_GET_ACTIVE_SESSION_COUNT_BY_TENANT_H2 : SQLQueries.SQL_GET_ACTIVE_SESSION_COUNT_BY_TENANT;
        try (PreparedStatement preparedStatement = connection.prepareStatement(sqlStmt)) {
            preparedStatement.setString(1, SessionMgtConstants.LAST_ACCESS_TIME);
            preparedStatement.setString(2, String.valueOf(minTimestamp));
            preparedStatement.setString(3, String.valueOf(currentTime));
            preparedStatement.setInt(4, tenantId);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    activeSessionCount = resultSet.getInt(1);
                }
            }
            IdentityDatabaseUtil.commitTransaction(connection);
        }
    } catch (DataAccessException | SQLException e) {
        throw new UserSessionException("Error while retrieving active session count of the tenant domain, " + tenantDomain, e);
    }
    return activeSessionCount;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException) DataAccessException(org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException)

Example 9 with UserSessionException

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

the class UserSessionStore method getSessionId.

/**
 * Method to get session Id list of a given user.
 *
 * @param user  user object
 * @param idpId id of the user's idp
 * @return the list of session ids
 * @throws UserSessionException if an error occurs when retrieving the session id list from the database
 */
public List<String> getSessionId(User user, int idpId) throws UserSessionException {
    List<String> sessionIdList = new ArrayList<>();
    int tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    try (Connection connection = IdentityDatabaseUtil.getSessionDBConnection(false)) {
        try (PreparedStatement preparedStatement = connection.prepareStatement(SQLQueries.SQL_GET_SESSIONS_BY_USER)) {
            preparedStatement.setString(1, user.getUserName());
            preparedStatement.setInt(2, tenantId);
            preparedStatement.setString(3, (user.getUserStoreDomain() == null) ? FEDERATED_USER_DOMAIN : user.getUserStoreDomain().toUpperCase());
            preparedStatement.setInt(4, idpId);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    sessionIdList.add(resultSet.getString(1));
                }
            }
        } catch (SQLException ex) {
            throw new UserSessionException("Error while retrieving session IDs of user: " + user.getLoggableUserId() + ".", ex);
        }
    } catch (SQLException e) {
        throw new UserSessionException("Error while retrieving session IDs of user: " + user.getLoggableUserId() + ".", e);
    }
    return sessionIdList;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) UserSessionException(org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException)

Example 10 with UserSessionException

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

Aggregations

UserSessionException (org.wso2.carbon.identity.application.authentication.framework.exception.UserSessionException)24 Connection (java.sql.Connection)14 PreparedStatement (java.sql.PreparedStatement)14 SQLException (java.sql.SQLException)14 ResultSet (java.sql.ResultSet)10 ArrayList (java.util.ArrayList)6 DataAccessException (org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException)6 AuthHistory (org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory)6 JdbcTemplate (org.wso2.carbon.database.utils.jdbc.JdbcTemplate)5 DuplicatedAuthUserException (org.wso2.carbon.identity.application.authentication.framework.exception.DuplicatedAuthUserException)5 SQLIntegrityConstraintViolationException (java.sql.SQLIntegrityConstraintViolationException)4 HashSet (java.util.HashSet)4 List (java.util.List)4 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4 Map (java.util.Map)3 Set (java.util.Set)3 TimeUnit (java.util.concurrent.TimeUnit)3 StringUtils (org.apache.commons.lang.StringUtils)3 Log (org.apache.commons.logging.Log)3 LogFactory (org.apache.commons.logging.LogFactory)3