List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Reproduces the problem with/* ww w .j ava 2 s. co m*/ * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>. * * @throws Exception if anything goes wrong */ @Test public void testAdminAccessBug() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous final Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put("java.naming.ldap.version", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); Attributes attributes = new BasicAttributes(true); Attribute objectClass = new BasicAttribute("objectClass"); objectClass.add("top"); objectClass.add("organizationalUnit"); attributes.put(objectClass); attributes.put("ou", "blah"); InitialDirContext ctx = new InitialDirContext(env); ctx.createSubcontext("ou=blah,ou=system", attributes); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.OBJECT_SCOPE); controls.setReturningAttributes(new String[] { "+" }); NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls); SearchResult result = list.next(); list.close(); Attribute creatorsName = result.getAttributes().get("creatorsName"); assertEquals("", creatorsName.get()); ctx.destroySubcontext("ou=blah,ou=system"); }
From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java
/** * Gets and returns the entries from the server. * // www.j a v a2s. c o m * @throws ToolCommandException * @throws NamingException */ public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException { // Connecting to the LDAP Server if (isDebugEnabled()) { notifyOutputListener("Connecting to LDAP server"); notifyOutputListener("Host: " + host); notifyOutputListener("Port: " + port); notifyOutputListener("User DN: " + user); notifyOutputListener("Base DN: " + baseDN); notifyOutputListener("Authentication: " + auth); } Hashtable env = new Hashtable(); env.put(Context.SECURITY_PRINCIPAL, user); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, auth); env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); DirContext ctx; try { ctx = new InitialDirContext(env); } catch (NamingException e) { throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage()); } // Setting up search scope SearchControls ctls = new SearchControls(); ctls.setSearchScope(scope); // Fetching entries try { return ctx.search(exportPoint, "(objectClass=*)", ctls); } catch (NamingException e) { throw new ToolCommandException("Could not retreive entries"); } }
From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java
/** * Returns the {@link SearchControls} object associated with the request. * * @param request/* www. ja va 2 s . c o m*/ * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls(SearchRequest request) { SearchControls controls = new SearchControls(); // Scope switch (request.getScope()) { case OBJECT: controls.setSearchScope(SearchControls.OBJECT_SCOPE); break; case ONELEVEL: controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); break; case SUBTREE: controls.setSearchScope(SearchControls.SUBTREE_SCOPE); break; default: controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); } // Returning attributes List<String> returningAttributes = new ArrayList<String>(); for (String attribute : request.getAttributes()) { returningAttributes.add(attribute); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if (returningAttributes.size() == 0) { returningAttributes.add("*"); //$NON-NLS-1$ } controls.setReturningAttributes(returningAttributes.toArray(new String[0])); // Size Limit controls.setCountLimit(request.getSizeLimit()); // Time Limit controls.setTimeLimit(request.getTimeLimit()); return controls; }
From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
protected boolean authenticate(String username) throws Exception { DirContext context = open();//ww w. j a va2 s . c o m 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 String[] attribs; if (userRoleName == null) { attribs = new String[] {}; } else { attribs = new String[] { userRoleName }; } constraints.setReturningAttributes(attribs); NamingEnumeration results = context.search(userBase, filter, constraints); if (results == null || !results.hasMore()) { log.error("No roles associated with user " + username); loginSucceeded = false; throw new FailedLoginException(); } SearchResult result = (SearchResult) results.next(); if (results.hasMore()) { // ignore for now } NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(userBase); 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) { return false; } ArrayList<String> roles = null; if (userRoleName != null) { roles = addAttributeValues(userRoleName, attrs, roles); } // check the credentials by binding to server // bindUser(context, dn); // if authenticated add more roles roles = getRoles(context, dn, username, roles); for (String role : roles) { groups.add(role); } if (groups.isEmpty()) { log.error("No roles associated with user " + username); loginSucceeded = false; throw new FailedLoginException(); } else loginSucceeded = true; } catch (CommunicationException e) { close(context); throw (LoginException) new FailedLoginException().initCause(e); } catch (NamingException e) { close(context); throw (LoginException) new FailedLoginException().initCause(e); } return true; }
From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
protected ArrayList<String> getRoles(DirContext context, String dn, String username, ArrayList<String> list) throws NamingException { if (list == null) { list = new ArrayList<String>(); }/*from w w w .j av a 2s . co m*/ if (roleName == null || "".equals(roleName)) { return list; } String filter = roleSearchMatchingFormat.format(new String[] { doRFC2254Encoding(dn), username }); SearchControls constraints = new SearchControls(); if (roleSearchSubtreeBool) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } NamingEnumeration results = context.search(roleBase, filter, constraints); while (results.hasMore()) { SearchResult result = (SearchResult) results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) { continue; } list = addAttributeValues(roleName, attrs, list); } return list; }
From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
/** * Gets all the user entities taken from the LDAP server, as taken from the * search-context given by the value of the attribute {@link #userBase}. * * @return A set containing all the relevant users found in the LDAP * directory.//from w ww . ja v a 2 s . com * @throws NamingException * Propagated from the LDAP communication layer. */ private Set<String> getAllUsersFromLDAP() throws NamingException { Set<String> result = new HashSet<String>(); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { "distinguishedName" }); NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, "(objectClass=" + userObjectClass + ")", sc); while (sr.hasMore()) { SearchResult r = sr.next(); result.add(r.getNameInNamespace()); } return result; }
From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
/** * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass} * and builds {@link User} based on search result. * * @param name/*from ww w. ja v a 2 s. c o m*/ * The userId which should be value of the field {@link #userIdAttribute} * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the * userId of this user and ldap connection information with which * the user was searched. Return null if such a user was not found. * @throws NamingException * Propagated by the underlying LDAP communication layer. */ private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { userIdAttribute }); sc.setCountLimit(1); StringBuilder builderFilter = new StringBuilder("(&("); builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=") .append(userObjectClass).append(")"); if (StringUtils.isNotEmpty(filter)) { builderFilter.append(filter).append(")"); } else { builderFilter.append(")"); } NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc); if (!sr.hasMore()) return null; SearchResult r = sr.next(); Attribute userName = r.getAttributes().get(userIdAttribute); if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(), restriction.getGroupMembershipLists(ldapContext))) return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext); return null; }
From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java
/** * Find account by account name./* ww w.java2 s . c o m*/ * * @param accountName the account name * @return the search result * @throws NamingException the naming exception */ protected SearchResult findAccountByAccountName(String accountName) throws NamingException { String searchFilter = String.format(searchFilterPattern, accountName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); InitialLdapContext ctx = new InitialLdapContext(env, null); try { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls); if (!results.hasMoreElements()) { throw new UserConfigLoaderException("LDAP Search returned no accounts"); } SearchResult searchResult = results.nextElement(); if (results.hasMoreElements()) { throw new UserConfigLoaderException("More than one account found in ldap search"); } return searchResult; } finally { ctx.close(); } }
From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java
/** * Reloads the tenants.// w w w .j a v a 2 s . c o m */ private void load(final ContextSource contextSource) { // create the ldapTemplate based on the context source. use a single source context to use the same connection // to support paging when configured final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext()); final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource); try { final List<User> userList = new ArrayList<>(); final List<Group> groupList = new ArrayList<>(); // group dn -> user identifiers lookup final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>(); // user dn -> user lookup final Map<String, User> userLookup = new HashMap<>(); if (performUserSearch) { // search controls final SearchControls userControls = new SearchControls(); userControls.setSearchScope(userSearchScope.ordinal()); // consider paging support for users final DirContextProcessor userProcessor; if (pageSize == null) { userProcessor = new NullDirContextProcessor(); } else { userProcessor = new PagedResultsDirContextProcessor(pageSize); } // looking for objects matching the user object class final AndFilter userFilter = new AndFilter(); userFilter.and(new EqualsFilter("objectClass", userObjectClass)); // if a filter has been provided by the user, we add it to the filter if (StringUtils.isNotBlank(userSearchFilter)) { userFilter.and(new HardcodedFilter(userSearchFilter)); } do { userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls, new AbstractContextMapper<User>() { @Override protected User doMapFromContext(DirContextOperations ctx) { // get the user identity final String identity = getUserIdentity(ctx); // build the user final User user = new User.Builder().identifierGenerateFromSeed(identity) .identity(identity).build(); // store the user for group member later userLookup.put(getReferencedUserValue(ctx), user); if (StringUtils.isNotBlank(userGroupNameAttribute)) { final Attribute attributeGroups = ctx.getAttributes() .get(userGroupNameAttribute); if (attributeGroups == null) { logger.warn("User group name attribute [" + userGroupNameAttribute + "] does not exist. Ignoring group membership."); } else { try { final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups .getAll(); while (groupValues.hasMoreElements()) { // store the group -> user identifier mapping groupToUserIdentifierMappings .computeIfAbsent(groupValues.next(), g -> new HashSet<>()) .add(user.getIdentifier()); } } catch (NamingException e) { throw new AuthorizationAccessException( "Error while retrieving user group name attribute [" + userIdentityAttribute + "]."); } } } return user; } }, userProcessor)); } while (hasMorePages(userProcessor)); } if (performGroupSearch) { final SearchControls groupControls = new SearchControls(); groupControls.setSearchScope(groupSearchScope.ordinal()); // consider paging support for groups final DirContextProcessor groupProcessor; if (pageSize == null) { groupProcessor = new NullDirContextProcessor(); } else { groupProcessor = new PagedResultsDirContextProcessor(pageSize); } // looking for objects matching the group object class AndFilter groupFilter = new AndFilter(); groupFilter.and(new EqualsFilter("objectClass", groupObjectClass)); // if a filter has been provided by the user, we add it to the filter if (StringUtils.isNotBlank(groupSearchFilter)) { groupFilter.and(new HardcodedFilter(groupSearchFilter)); } do { groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls, new AbstractContextMapper<Group>() { @Override protected Group doMapFromContext(DirContextOperations ctx) { final String dn = ctx.getDn().toString(); // get the group identity final String name = getGroupName(ctx); // get the value of this group that may associate it to users final String referencedGroupValue = getReferencedGroupValue(ctx); if (!StringUtils.isBlank(groupMemberAttribute)) { Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute); if (attributeUsers == null) { logger.warn("Group member attribute [" + groupMemberAttribute + "] does not exist. Ignoring group membership."); } else { try { final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers .getAll(); while (userValues.hasMoreElements()) { final String userValue = userValues.next(); if (performUserSearch) { // find the user by it's referenced attribute and add the identifier to this group final User user = userLookup.get(userValue); // ensure the user is known if (user != null) { groupToUserIdentifierMappings .computeIfAbsent(referencedGroupValue, g -> new HashSet<>()) .add(user.getIdentifier()); } else { logger.warn(String.format( "%s contains member %s but that user was not found while searching users. Ignoring group membership.", name, userValue)); } } else { // since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn final String userDn = userValue; final String userIdentity; if (useDnForUserIdentity) { // use the user value to avoid the unnecessary look up userIdentity = userDn; } else { // lookup the user to extract the user identity userIdentity = getUserIdentity( (DirContextAdapter) ldapTemplate .lookup(userDn)); } // build the user final User user = new User.Builder() .identifierGenerateFromSeed(userIdentity) .identity(userIdentity).build(); // add this user userList.add(user); groupToUserIdentifierMappings .computeIfAbsent(referencedGroupValue, g -> new HashSet<>()) .add(user.getIdentifier()); } } } catch (NamingException e) { throw new AuthorizationAccessException( "Error while retrieving group name attribute [" + groupNameAttribute + "]."); } } } // build this group final Group.Builder groupBuilder = new Group.Builder() .identifierGenerateFromSeed(name).name(name); // add all users that were associated with this referenced group attribute if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) { groupToUserIdentifierMappings.remove(referencedGroupValue) .forEach(userIdentifier -> groupBuilder.addUser(userIdentifier)); } return groupBuilder.build(); } }, groupProcessor)); } while (hasMorePages(groupProcessor)); // any remaining groupDn's were referenced by a user but not found while searching groups groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> { logger.warn(String.format( "[%s] are members of %s but that group was not found while searching users. Ignoring group membership.", StringUtils.join(userIdentifiers, ", "), referencedGroupValue)); }); } else { // since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn // groups are not being searched so lookup any groups identified while searching users groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> { final String groupName; if (useDnForGroupName) { // use the dn to avoid the unnecessary look up groupName = groupDn; } else { groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn)); } // define the group final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName) .name(groupName); // add each user userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier)); // build the group groupList.add(groupBuilder.build()); }); } // record the updated tenants tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList))); } finally { singleContextSource.destroy(); } }
From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java
public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse, LDAPResolver ldapResolver) throws PIPException { /*/*from w w w .j a v a 2 s.c o m*/ * Check with the resolver to get the base string */ String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder); if (stringBase == null) { this.logger.warn(this.getName() + " does not handle " + pipRequest.toString()); return; } /* * Get the filter string */ String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder); /* * Check the cache */ Cache<String, PIPResponse> cache = this.getCache(); String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter); if (cache != null) { PIPResponse pipResponse = cache.getIfPresent(cacheKey); if (pipResponse != null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Returning cached response: " + pipResponse); } mutablePIPResponse.addAttributes(pipResponse.getAttributes()); return; } } /* * Not in the cache, so set up the LDAP query session */ DirContext dirContext = null; PIPResponse pipResponse = null; try { /* * Create the DirContext */ dirContext = new InitialDirContext(this.ldapEnvironment); /* * Set up the search controls */ SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(this.ldapScope); /* * Do the search */ NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter, searchControls); if (namingEnumeration != null && namingEnumeration.hasMore()) { while (namingEnumeration.hasMore()) { List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next()); if (listAttributes != null && listAttributes.size() > 0) { mutablePIPResponse.addAttributes(listAttributes); } } } /* * Put in the cache */ if (cache != null) { cache.put(cacheKey, pipResponse); } } catch (NamingException ex) { this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex); } finally { if (dirContext != null) { try { dirContext.close(); } catch (Exception ex) { this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex); } } } }