log.debug("Create the LDAP initial context.");
}
try {
context = open();
} catch (NamingException ne) {
FailedLoginException ex = new FailedLoginException("Error opening LDAP connection");
ex.initCause(ne);
throw ex;
}
if (!isLoginPropertySet(USER_SEARCH_MATCHING))
return false;
userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();
try {
String filter = userSearchMatchingFormat.format(new String[] {
username
});
SearchControls constraints = new SearchControls();
if (userSearchSubtreeBool) {
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
// setup attributes
List<String> list = new ArrayList<String>();
if (isLoginPropertySet(USER_ROLE_NAME)) {
list.add(getLDAPPropertyValue(USER_ROLE_NAME));
}
String[] attribs = new String[list.size()];
list.toArray(attribs);
constraints.setReturningAttributes(attribs);
if (log.isDebugEnabled()) {
log.debug("Get the user DN.");
log.debug("Looking for the user in LDAP with ");
log.debug(" base DN: " + getLDAPPropertyValue(USER_BASE));
log.debug(" filter: " + filter);
}
NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(USER_BASE), filter, constraints);
if (results == null || !results.hasMore()) {
log.warn("User " + username + " not found in LDAP.");
throw new FailedLoginException("User " + username + " not found in LDAP.");
}
SearchResult result = results.next();
if (results.hasMore()) {
// ignore for now
}
NameParser parser = context.getNameParser("");
Name contextName = parser.parse(context.getNameInNamespace());
Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE));
Name entryName = parser.parse(result.getName());
Name name = contextName.addAll(baseName);
name = name.addAll(entryName);
String dn = name.toString();
Attributes attrs = result.getAttributes();
if (attrs == null) {
throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
}
List<String> roles = null;
if (isLoginPropertySet(USER_ROLE_NAME)) {
roles = addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles);
}
// check the credentials by binding to server
if (bindUser(context, dn, password)) {
// if authenticated add more roles
roles = getRoles(context, dn, username, roles);
if (log.isDebugEnabled()) {
log.debug("Roles " + roles + " for user " + username);
}
for (int i = 0; i < roles.size(); i++) {
groups.add(new GroupPrincipal(roles.get(i)));
}
} else {
throw new FailedLoginException("Password does not match for user: " + username);
}
} catch (CommunicationException e) {
FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
ex.initCause(e);
throw ex;
} catch (NamingException e) {
if (context != null) {
close(context);
}
FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
ex.initCause(e);
throw ex;
}
return true;
}