use of javax.naming.directory.SearchResult in project jetty.project by eclipse.
the class LdapLoginModule method getUserAttributes.
/**
* attempts to get the users LDAP attributes from the users context
* <p>
* NOTE: this is not an user authenticated operation
*
* @param username
* @return
* @throws LoginException
*/
private Attributes getUserAttributes(String username) throws LoginException {
Attributes attributes = null;
SearchResult result;
try {
result = findUser(username);
attributes = result.getAttributes();
} catch (NamingException e) {
throw new LoginException("Root context binding failure.");
}
return attributes;
}
use of javax.naming.directory.SearchResult in project jetty.project by eclipse.
the class LdapLoginModule method findUser.
private SearchResult findUser(String username) throws NamingException, LoginException {
SearchControls ctls = new SearchControls();
ctls.setCountLimit(1);
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass={0})({1}={2}))";
if (LOG.isDebugEnabled())
LOG.debug("Searching for user " + username + " with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn);
Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username };
NamingEnumeration<SearchResult> results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);
if (LOG.isDebugEnabled())
LOG.debug("Found user?: " + results.hasMoreElements());
if (!results.hasMoreElements()) {
throw new LoginException("User not found.");
}
return (SearchResult) results.nextElement();
}
use of javax.naming.directory.SearchResult in project Openfire by igniterealtime.
the class LdapGroupTester method getGroups.
/**
* Returns fist N groups found in LDAP. The returned groups are only able to return their name,
* description and count of members. Count of members is considering all values that were found
* in the member field.
*
* @param maxGroups max number of groups to return.
* @return fist N groups found in the LDAP.
*/
public Collection<Group> getGroups(int maxGroups) {
Collection<Group> groups = new ArrayList<>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on group name field.
Control[] searchControl = new Control[] { new SortControl(new String[] { manager.getGroupNameField() }, Control.NONCRITICAL) };
ctx.setRequestControls(searchControl);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
// Attributes to return for each group
String[] standardAttributes = new String[3];
standardAttributes[0] = manager.getGroupNameField();
standardAttributes[1] = manager.getGroupDescriptionField();
standardAttributes[2] = manager.getGroupMemberField();
searchControls.setReturningAttributes(standardAttributes);
// Limit results to those we'll need to process
searchControls.setCountLimit(maxGroups);
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
Attributes attributes = ((SearchResult) answer.next()).getAttributes();
String groupName = (String) attributes.get(manager.getGroupNameField()).get();
String description = "";
int elements = 0;
try {
description = ((String) attributes.get(manager.getGroupDescriptionField()).get());
} catch (NullPointerException e) {
// Do nothing since the group description field was not found
} catch (Exception e) {
Log.error("Error retrieving group description", e);
}
Attribute memberField = attributes.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
ne.next();
elements = elements + 1;
}
}
// Build Group with found information
groups.add(new Group(groupName, description, elements));
}
// Close the enumeration.
answer.close();
} catch (Exception e) {
Log.error(e.getMessage(), e);
} finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
return groups;
}
use of javax.naming.directory.SearchResult in project Openfire by igniterealtime.
the class LdapGroupProvider method processGroup.
private Group processGroup(LdapContext ctx, Attributes a) throws NamingException {
XMPPServer server = XMPPServer.getInstance();
String serverName = server.getServerInfo().getXMPPDomain();
// Build `3 groups.
// group 1: uid=
// group 2: rest of the text until first comma
// group 3: rest of the text
Pattern pattern = Pattern.compile("(?i)(^" + manager.getUsernameField() + "=)([^,]+)(.+)");
// We have to process Active Directory differently.
boolean isAD = manager.getUsernameField().equals("sAMAccountName");
String[] returningAttributes = isAD ? new String[] { "distinguishedName", manager.getUsernameField() } : new String[] { manager.getUsernameField() };
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(returningAttributes);
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
String name;
String description;
try {
name = ((String) ((a.get(manager.getGroupNameField())).get()));
} catch (Exception e) {
name = "";
}
try {
description = ((String) ((a.get(manager.getGroupDescriptionField())).get()));
} catch (Exception e) {
description = "";
}
Set<JID> members = new TreeSet<>();
Attribute memberField = a.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
String username = (String) ne.next();
// If not posix mode, each group member is stored as a full DN.
if (!manager.isPosixMode()) {
try {
// Try to find the username with a regex pattern match.
Matcher matcher = pattern.matcher(username);
if (matcher.matches() && matcher.groupCount() == 3) {
// The username is in the DN, no additional search needed
username = matcher.group(2);
} else // The regex pattern match failed. This will happen if the
// the member DN's don't use the standard username field. For
// example, Active Directory has a username field of
// sAMAccountName, but stores group members as "CN=...".
{
// Create an LDAP name with the full DN.
LdapName ldapName = new LdapName(username);
// Turn the LDAP name into something we can use in a
// search by stripping off the comma.
StringBuilder userFilter = new StringBuilder();
userFilter.append("(&(");
userFilter.append(ldapName.get(ldapName.size() - 1));
userFilter.append(')');
userFilter.append(MessageFormat.format(manager.getSearchFilter(), "*"));
userFilter.append(')');
NamingEnumeration usrAnswer = ctx.search("", userFilter.toString(), searchControls);
if (usrAnswer != null && usrAnswer.hasMoreElements()) {
SearchResult searchResult = null;
// Iterate through the entire set to find a matching distinguished name.
while (usrAnswer.hasMoreElements()) {
searchResult = (SearchResult) usrAnswer.nextElement();
Attributes attrs = searchResult.getAttributes();
if (isAD) {
Attribute userdnAttr = attrs.get("distinguishedName");
if (username.equals((String) userdnAttr.get())) {
// Exact match found, use it.
username = (String) attrs.get(manager.getUsernameField()).get();
break;
}
} else {
// No iteration occurs here, which is probably a bug.
username = (String) attrs.get(manager.getUsernameField()).get();
break;
}
}
}
// Close the enumeration.
usrAnswer.close();
}
} catch (Exception e) {
// TODO: A NPE is occuring here
Log.error(e.getMessage(), e);
}
}
// it passes the filter.
try {
JID userJID;
int position = username.indexOf("@" + serverName);
// Create JID of local user if JID does not match a component's JID
if (position == -1) {
// In order to lookup a username from the manager, the username
// must be a properly escaped JID node.
String escapedUsername = JID.escapeNode(username);
if (!escapedUsername.equals(username)) {
// Check if escaped username is valid
userManager.getUser(escapedUsername);
}
// No exception, so the user must exist. Add the user as a group
// member using the escaped username.
userJID = server.createJID(escapedUsername, null);
} else {
// This is a JID of a component or node of a server's component
String node = username.substring(0, position);
String escapedUsername = JID.escapeNode(node);
userJID = new JID(escapedUsername + "@" + serverName);
}
members.add(userJID);
} catch (UserNotFoundException e) {
// So, we want to simply ignore the user as a group member.
if (manager.isDebugEnabled()) {
Log.debug("LdapGroupProvider: User not found: " + username);
}
}
}
// Close the enumeration.
ne.close();
}
if (manager.isDebugEnabled()) {
Log.debug("LdapGroupProvider: Adding group \"" + name + "\" with " + members.size() + " members.");
}
Collection<JID> admins = Collections.emptyList();
return new Group(name, description, members, admins);
}
use of javax.naming.directory.SearchResult in project Openfire by igniterealtime.
the class LdapManager method lookupExistence.
/**
* Looks up an LDAP object by its DN and returns <tt>true</tt> if
* the search was successful.
*
* @param ctx the Context to use for the lookup.
* @param dn the object's dn to lookup.
* @return true if the lookup was successful.
* @throws NamingException if login credentials were wrong.
*/
private Boolean lookupExistence(InitialDirContext ctx, String dn, String[] returnattrs) throws NamingException {
boolean debug = Log.isDebugEnabled();
if (debug) {
Log.debug("LdapManager: In lookupExistence(ctx, dn, returnattrs), searchdn is: " + dn);
}
// Bind to the object's DN
ctx.addToEnvironment(Context.PROVIDER_URL, getProviderURL(dn));
String filter = "(&(objectClass=*))";
SearchControls srcnt = new SearchControls();
srcnt.setSearchScope(SearchControls.OBJECT_SCOPE);
srcnt.setReturningAttributes(returnattrs);
NamingEnumeration<SearchResult> answer = null;
try {
answer = ctx.search("", filter, srcnt);
} catch (javax.naming.NameNotFoundException nex) {
// DN not found
} catch (NamingException ex) {
throw ex;
}
if (answer == null || !answer.hasMoreElements()) {
Log.debug("LdapManager: .... lookupExistence: DN not found.");
return false;
} else {
Log.debug("LdapManager: .... lookupExistence: DN found.");
return true;
}
}
Aggregations