use of javax.naming.directory.SearchControls in project zeppelin by apache.
the class LdapRealm method getUserDn.
/**
* Returns the LDAP User Distinguished Name (DN) to use when acquiring an
* {@link javax.naming.ldap.LdapContext LdapContext} from the
* {@link LdapContextFactory}.
* <p/>
* If the the {@link #getUserDnTemplate() userDnTemplate} property has been
* set, this implementation will construct the User DN by substituting the
* specified {@code principal} into the configured template. If the
* {@link #getUserDnTemplate() userDnTemplate} has not been set, the method
* argument will be returned directly (indicating that the submitted
* authentication token principal <em>is</em> the User DN).
*
* @param principal
* the principal to substitute into the configured
* {@link #getUserDnTemplate() userDnTemplate}.
* @return the constructed User DN to use at runtime when acquiring an
* {@link javax.naming.ldap.LdapContext}.
* @throws IllegalArgumentException
* if the method argument is null or empty
* @throws IllegalStateException
* if the {@link #getUserDnTemplate userDnTemplate} has not been
* set.
* @see LdapContextFactory#getLdapContext(Object, Object)
*/
@Override
protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException {
String userDn;
Matcher matchedPrincipal = matchPrincipal(principal);
String userSearchBase = getUserSearchBase();
String userSearchAttributeName = getUserSearchAttributeName();
// If not searching use the userDnTemplate and return.
if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) {
userDn = expandTemplate(userDnTemplate, matchedPrincipal);
if (log.isDebugEnabled()) {
log.debug("LDAP UserDN and Principal: " + userDn + "," + principal);
}
return userDn;
}
// Create the searchBase and searchFilter from config.
String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
String searchFilter = null;
if (userSearchFilter == null) {
if (userSearchAttributeName == null) {
searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass());
} else {
searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(), userSearchAttributeName, expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal));
}
} else {
searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
}
SearchControls searchControls = getUserSearchControls();
// Search for userDn and return.
LdapContext systemLdapCtx = null;
NamingEnumeration<SearchResult> searchResultEnum = null;
try {
systemLdapCtx = getContextFactory().getSystemLdapContext();
if (log.isDebugEnabled()) {
log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase + "," + searchFilter + "," + userSearchScope);
}
searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls);
// SearchResults contains all the entries in search scope
if (searchResultEnum.hasMore()) {
SearchResult searchResult = searchResultEnum.next();
userDn = searchResult.getNameInNamespace();
if (log.isDebugEnabled()) {
log.debug("UserDN Returned,Principal: " + userDn + "," + principal);
}
return userDn;
} else {
throw new IllegalArgumentException("Illegal principal name: " + principal);
}
} catch (AuthenticationException ne) {
ne.printStackTrace();
throw new IllegalArgumentException("Illegal principal name: " + principal);
} catch (NamingException ne) {
throw new IllegalArgumentException("Hit NamingException: " + ne.getMessage());
} finally {
try {
if (searchResultEnum != null) {
searchResultEnum.close();
}
} catch (NamingException ne) {
// Ignore exception on close.
} finally {
LdapUtils.closeContext(systemLdapCtx);
}
}
}
use of javax.naming.directory.SearchControls in project zeppelin by apache.
the class GetUserList method getUserList.
/**
* function to extract users from Zeppelin LdapRealm
*/
public List<String> getUserList(LdapRealm r, String searchText) {
List<String> userList = new ArrayList<>();
if (LOG.isDebugEnabled()) {
LOG.debug("SearchText: " + searchText);
}
String userAttribute = r.getUserSearchAttributeName();
String userSearchRealm = r.getUserSearchBase();
String userObjectClass = r.getUserObjectClass();
JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
try {
LdapContext ctx = CF.getSystemLdapContext();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { userAttribute };
constraints.setReturningAttributes(attrIDs);
NamingEnumeration result = ctx.search(userSearchRealm, "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=" + searchText + "))", constraints);
while (result.hasMore()) {
Attributes attrs = ((SearchResult) result.next()).getAttributes();
if (attrs.get(userAttribute) != null) {
String currentUser;
if (r.getUserLowerCase()) {
LOG.debug("userLowerCase true");
currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
} else {
LOG.debug("userLowerCase false");
currentUser = (String) attrs.get(userAttribute).get();
}
if (LOG.isDebugEnabled()) {
LOG.debug("CurrentUser: " + currentUser);
}
userList.add(currentUser.trim());
}
}
} catch (Exception e) {
LOG.error("Error retrieving User list from Ldap Realm", e);
}
return userList;
}
use of javax.naming.directory.SearchControls 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.SearchControls 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.SearchControls 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);
}
Aggregations