//~ Methods ========================================================================================================
public LdapUserDetails authenticate(final String username, final String password) {
// locate the user and check the password
LdapUserDetails user = null;
Iterator dns = getUserDns(username).iterator();
LdapTemplate ldapTemplate = new LdapTemplate(getInitialDirContextFactory());
while (dns.hasNext() && (user == null)) {
final String userDn = (String) dns.next();
if (ldapTemplate.nameExists(userDn)) {
LdapUserDetailsImpl.Essence userEssence = (LdapUserDetailsImpl.Essence)
ldapTemplate.retrieveEntry(userDn, getUserDetailsMapper(), getUserAttributes());
userEssence.setUsername(username);
user = userEssence.createUserDetails();
}
}
if ((user == null) && (getUserSearch() != null)) {
user = getUserSearch().searchForUser(username);
}
if (user == null) {
throw new UsernameNotFoundException(username);
}
String retrievedPassword = user.getPassword();
if (retrievedPassword != null) {
if (!verifyPassword(password, retrievedPassword)) {
throw new BadCredentialsException(messages.getMessage(
"PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}
return user;
}
if (logger.isDebugEnabled()) {
logger.debug("Password attribute wasn't retrieved for user '" + username + "' using mapper "
+ getUserDetailsMapper() + ". Performing LDAP compare of password attribute '" + passwordAttributeName
+ "'");
}
String encodedPassword = passwordEncoder.encodePassword(password, null);
byte[] passwordBytes = LdapUtils.getUtf8Bytes(encodedPassword);
if (!ldapTemplate.compare(user.getDn(), passwordAttributeName, passwordBytes)) {
throw new BadCredentialsException(messages.getMessage("PasswordComparisonAuthenticator.badCredentials",
"Bad credentials"));
}
return user;