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);
}
}
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);
}
}
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;
}
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;
}
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);
}
Aggregations