Search in sources :

Example 1 with IncorrectResultSizeDataAccessException

use of org.springframework.dao.IncorrectResultSizeDataAccessException in project cas by apereo.

the class QueryDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    if (StringUtils.isBlank(this.sql) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly. " + "No SQL statement or JDBC template is found.");
    }
    final Map<String, Object> attributes = new LinkedHashMap<>(this.principalAttributeMap.size());
    final String username = credential.getUsername();
    final String password = credential.getPassword();
    try {
        final Map<String, Object> dbFields = getJdbcTemplate().queryForMap(this.sql, username);
        final String dbPassword = (String) dbFields.get(this.fieldPassword);
        if (StringUtils.isNotBlank(originalPassword) && !matches(originalPassword, dbPassword) || StringUtils.isBlank(originalPassword) && !StringUtils.equals(password, dbPassword)) {
            throw new FailedLoginException("Password does not match value on record.");
        }
        if (StringUtils.isNotBlank(this.fieldDisabled)) {
            final Object dbDisabled = dbFields.get(this.fieldDisabled);
            if (dbDisabled != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbDisabled.toString())) || dbDisabled.equals(Integer.valueOf(1)))) {
                throw new AccountDisabledException("Account has been disabled");
            }
        }
        if (StringUtils.isNotBlank(this.fieldExpired)) {
            final Object dbExpired = dbFields.get(this.fieldExpired);
            if (dbExpired != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbExpired.toString())) || dbExpired.equals(Integer.valueOf(1)))) {
                throw new AccountPasswordMustChangeException("Password has expired");
            }
        }
        this.principalAttributeMap.entrySet().forEach(a -> {
            final Object attribute = dbFields.get(a.getKey());
            if (attribute != null) {
                LOGGER.debug("Found attribute [{}] from the query results", a);
                if (attribute != null) {
                    LOGGER.debug("Found attribute [{}] from the query results", a);
                    final String principalAttrName = a.getValue();
                    attributes.put(principalAttrName, attribute.toString());
                } else {
                    LOGGER.warn("Requested attribute [{}] could not be found in the query results", a.getKey());
                }
            }
        });
    } catch (final IncorrectResultSizeDataAccessException e) {
        if (e.getActualSize() == 0) {
            throw new AccountNotFoundException(username + " not found with SQL query");
        }
        throw new FailedLoginException("Multiple records found for " + username);
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }
    return createHandlerResult(credential, this.principalFactory.createPrincipal(username, attributes), null);
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) GeneralSecurityException(java.security.GeneralSecurityException) PreventedException(org.apereo.cas.authentication.PreventedException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) DataAccessException(org.springframework.dao.DataAccessException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with IncorrectResultSizeDataAccessException

use of org.springframework.dao.IncorrectResultSizeDataAccessException in project spring-security by spring-projects.

the class ActiveDirectoryLdapAuthenticationProvider method searchForUser.

private DirContextOperations searchForUser(DirContext context, String username) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String bindPrincipal = createBindPrincipal(username);
    String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);
    try {
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context, searchControls, searchRoot, searchFilter, new Object[] { bindPrincipal });
    } catch (IncorrectResultSizeDataAccessException incorrectResults) {
        // rethrow
        if (incorrectResults.getActualSize() != 0) {
            throw incorrectResults;
        }
        // If we found no results, then the username/password did not match
        UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException("User " + username + " not found in directory.", incorrectResults);
        throw badCredentials(userNameNotFoundException);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) SearchControls(javax.naming.directory.SearchControls)

Example 3 with IncorrectResultSizeDataAccessException

use of org.springframework.dao.IncorrectResultSizeDataAccessException in project spring-security by spring-projects.

the class FilterBasedLdapUserSearch method searchForUser.

// ~ Methods
// ========================================================================================================
/**
	 * Return the LdapUserDetails containing the user's information
	 *
	 * @param username the username to search for.
	 *
	 * @return An LdapUserDetails object containing the details of the located user's
	 * directory entry
	 *
	 * @throws UsernameNotFoundException if no matching entry is found.
	 */
public DirContextOperations searchForUser(String username) {
    if (logger.isDebugEnabled()) {
        logger.debug("Searching for user '" + username + "', with user search " + this);
    }
    SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);
    template.setSearchControls(searchControls);
    try {
        return template.searchForSingleEntry(searchBase, searchFilter, new String[] { username });
    } catch (IncorrectResultSizeDataAccessException notFound) {
        if (notFound.getActualSize() == 0) {
            throw new UsernameNotFoundException("User " + username + " not found in directory.");
        }
        // rethrow
        throw notFound;
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Example 4 with IncorrectResultSizeDataAccessException

use of org.springframework.dao.IncorrectResultSizeDataAccessException in project cas by apereo.

the class QueryAndEncodeDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    if (StringUtils.isBlank(this.sql) || StringUtils.isBlank(this.algorithmName) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly");
    }
    final String username = transformedCredential.getUsername();
    try {
        final Map<String, Object> values = getJdbcTemplate().queryForMap(this.sql, username);
        final String digestedPassword = digestEncodedPassword(transformedCredential.getPassword(), values);
        if (!values.get(this.passwordFieldName).equals(digestedPassword)) {
            throw new FailedLoginException("Password does not match value on record.");
        }
        if (StringUtils.isNotBlank(this.expiredFieldName)) {
            final Object dbExpired = values.get(this.expiredFieldName);
            if (dbExpired != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbExpired.toString())) || dbExpired.equals(Integer.valueOf(1)))) {
                throw new AccountPasswordMustChangeException("Password has expired");
            }
        }
        if (StringUtils.isNotBlank(this.disabledFieldName)) {
            final Object dbDisabled = values.get(this.disabledFieldName);
            if (dbDisabled != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbDisabled.toString())) || dbDisabled.equals(Integer.valueOf(1)))) {
                throw new AccountDisabledException("Account has been disabled");
            }
        }
        return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username), null);
    } catch (final IncorrectResultSizeDataAccessException e) {
        if (e.getActualSize() == 0) {
            throw new AccountNotFoundException(username + " not found with SQL query");
        }
        throw new FailedLoginException("Multiple records found for " + username);
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) GeneralSecurityException(java.security.GeneralSecurityException) PreventedException(org.apereo.cas.authentication.PreventedException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) DataAccessException(org.springframework.dao.DataAccessException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Example 5 with IncorrectResultSizeDataAccessException

use of org.springframework.dao.IncorrectResultSizeDataAccessException in project cobar by alibaba.

the class CobarAdapter method getCurrentTimeMillis.

@Override
public Pair<Long, Long> getCurrentTimeMillis() {
    return (Pair<Long, Long>) getJdbcTemplate().execute(new StatementCallback() {

        @Override
        public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                long time1 = System.currentTimeMillis();
                rs = stmt.executeQuery("show @@status.time");
                long time2 = System.currentTimeMillis();
                if (rs.next()) {
                    return new Pair<Long, Long>(time1 + (time2 - time1) / 2, rs.getLong(1));
                } else {
                    throw new IncorrectResultSizeDataAccessException(1, 0);
                }
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        }
    });
}
Also used : StatementCallback(org.springframework.jdbc.core.StatementCallback) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) Pair(com.alibaba.cobar.manager.util.Pair)

Aggregations

IncorrectResultSizeDataAccessException (org.springframework.dao.IncorrectResultSizeDataAccessException)6 GeneralSecurityException (java.security.GeneralSecurityException)2 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)2 FailedLoginException (javax.security.auth.login.FailedLoginException)2 PreventedException (org.apereo.cas.authentication.PreventedException)2 AccountDisabledException (org.apereo.cas.authentication.exceptions.AccountDisabledException)2 AccountPasswordMustChangeException (org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)2 DataAccessException (org.springframework.dao.DataAccessException)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2 Pair (com.alibaba.cobar.manager.util.Pair)1 ResultSet (java.sql.ResultSet)1 Statement (java.sql.Statement)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 PartialResultException (javax.naming.PartialResultException)1 SearchControls (javax.naming.directory.SearchControls)1 SearchResult (javax.naming.directory.SearchResult)1 StatementCallback (org.springframework.jdbc.core.StatementCallback)1 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)1 DirContextOperations (org.springframework.ldap.core.DirContextOperations)1