List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java
public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException { if (type != group && type != iperson) return new EntityIdentifier[0]; // Guarantee that LDAP injection is prevented by replacing LDAP special characters // with escaped versions of the character query = LdapEncoder.filterEncode(query); ArrayList ids = new ArrayList(); switch (method) { case STARTS_WITH: query = query + "*"; break;/*from w ww.ja v a 2s . c om*/ case ENDS_WITH: query = "*" + query; break; case CONTAINS: query = "*" + query + "*"; break; } query = namefield + "=" + query; DirContext context = getConnection(); NamingEnumeration userlist = null; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { keyfield }); try { userlist = context.search(usercontext, query, sc); ArrayList keys = new ArrayList(); processLdapResults(userlist, keys); String[] k = (String[]) keys.toArray(new String[0]); for (int i = 0; i < k.length; i++) { ids.add(new EntityIdentifier(k[i], iperson)); } return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]); } catch (NamingException nex) { throw new GroupsException("LDAPGroupStore: Unable to perform filter " + query, nex); } }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * This method returns the proper search controls to be used when querying the LDAP.. */// w w w . j av a 2 s . c om protected SearchControls getSearchControls() { SearchControls sc = new SearchControls(); sc.setSearchScope(_ldapSearchScope == null || _ldapSearchScope.equalsIgnoreCase("ONELEVEL") ? SearchControls.ONELEVEL_SCOPE : SearchControls.SUBTREE_SCOPE); return sc; }
From source file:org.ballerinalang.auth.ldap.nativeimpl.GetLdapScopesOfUser.java
private String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase, CommonLdapConfiguration ldapAuthConfig) throws UserStoreException, NamingException { if (userName == null) { throw new BallerinaException("userName value is null."); }/*from ww w . j a v a2s. c o m*/ SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Load normal roles with the user String searchFilter = ldapAuthConfig.getGroupNameListFilter(); String roleNameProperty = ldapAuthConfig.getGroupNameAttribute(); String membershipProperty = ldapAuthConfig.getMembershipAttribute(); String nameInSpace = this.getNameInSpaceForUserName(userName, ldapConfiguration); if (membershipProperty == null || membershipProperty.length() < 1) { throw new BallerinaException("membershipAttribute not set in configuration"); } String membershipValue; if (nameInSpace != null) { LdapName ldn = new LdapName(nameInSpace); if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) { // membership value of posixGroup is not DN of the user List rdns = ldn.getRdns(); membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString(); } else { membershipValue = escapeLdapNameForFilter(ldn); } } else { return new String[0]; } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))"; String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); if (LOG.isDebugEnabled()) { LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty); } List<String> list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty, false); return list.toArray(new String[list.size()]); }
From source file:org.ballerinalang.auth.ldap.util.LdapUtils.java
/** * Searches the corresponding name for a given username from LDAP. * * @param userName Given username * @param searchBase LDAP search base * @param searchFilter LDAP search filter * @param dirContext Directory naming context * @return Associated name for the given username * @throws UserStoreException if there is any exception occurs during the process * @throws NamingException if there is any exception occurs during the process *///w ww . j a va 2 s . c o m public static String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter, DirContext dirContext) throws UserStoreException, NamingException { if (userName == null) { throw new UserStoreException("userName value is null."); } String userDN = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] searchBases = searchBase.split("#"); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (!(answer.hasMore())) { continue; } SearchResult userObj = answer.next(); if (userObj != null) { //no need to decode since , if decoded the whole string, can't be encoded again //eg CN=Hello\,Ok=test\,test, OU=Industry userDN = userObj.getNameInNamespace(); break; } } if (LOG.isDebugEnabled()) { LOG.debug("Name in space for " + userName + " is " + userDN); } } finally { LdapUtils.closeNamingEnumeration(answer); } return userDN; }
From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java
private static String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase, CommonLdapConfiguration ldapAuthConfig, DirContext ldapConnectionContext) throws UserStoreException, NamingException { if (userName == null) { throw new BallerinaException("userName value is null."); }/* w w w. j a v a 2 s. c o m*/ SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Load normal roles with the user String searchFilter = ldapAuthConfig.getGroupNameListFilter(); String roleNameProperty = ldapAuthConfig.getGroupNameAttribute(); String membershipProperty = ldapAuthConfig.getMembershipAttribute(); String nameInSpace = getNameInSpaceForUserName(userName, ldapAuthConfig, ldapConnectionContext); if (membershipProperty == null || membershipProperty.length() < 1) { throw new BallerinaException("membershipAttribute not set in configuration"); } String membershipValue; if (nameInSpace != null) { LdapName ldn = new LdapName(nameInSpace); if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) { // membership value of posixGroup is not DN of the user List rdns = ldn.getRdns(); membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString(); } else { membershipValue = escapeLdapNameForFilter(ldn); } } else { return new String[0]; } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))"; String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); if (LOG.isDebugEnabled()) { LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty); } List<String> list = getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty, ldapConnectionContext); return list.toArray(new String[list.size()]); }
From source file:org.beangle.security.ldap.connect.SimpleLdapUserStore.java
public String getUserDN(String uid) { DirContext ctx = getContext(); if (ctx == null) return null; String result = null;/*from w ww. j a v a 2 s .c o m*/ String condition = StrUtils.concat(uidName, "=", uid); try { String attrList[] = { uidName }; SearchControls constraints = new SearchControls(); constraints.setSearchScope(2); constraints.setReturningAttributes(attrList); NamingEnumeration<SearchResult> results = ctx.search(base, condition, constraints); if (results.hasMore()) { SearchResult si = results.next(); result = StrUtils.concat(si.getName(), ",", base); } results.close(); results = null; } catch (Throwable e) { logger.error("Ldap search error,uid=" + uid, e); } return result; }
From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java
/** * Performs an LDAP compare operation of the value of an attribute for a particular directory entry. * * @param dn the entry who's attribute is to be used * @param attributeName the attribute who's value we want to compare * @param value the value to be checked against the directory value * * @return true if the supplied value matches that in the directory *///from w ww .j a v a2s . c om public boolean compare(final String dn, final String attributeName, final Object value) { final String comparisonFilter = "(" + attributeName + "={0})"; class LdapCompareCallback implements ContextExecutor { public Object executeWithContext(DirContext ctx) throws NamingException { SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(NO_ATTRS); ctls.setSearchScope(SearchControls.OBJECT_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(dn, comparisonFilter, new Object[] { value }, ctls); Boolean match = Boolean.valueOf(results.hasMore()); LdapUtils.closeEnumeration(results); return match; } } Boolean matches = (Boolean) executeReadOnly(new LdapCompareCallback()); return matches.booleanValue(); }
From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java
/** * Performs a search using the supplied filter and returns the values of each named attribute * found in all entries matched by the search. Note that one directory entry may have several values for the * attribute. Intended for role searches and similar scenarios. * * @param base the DN to search in/*from w w w .j a v a2s. c o m*/ * @param filter search filter to use * @param params the parameters to substitute in the search filter * @param attributeNames the attributes' values that are to be retrieved. * * @return the set of String values for each attribute found in all the matching entries. * The attribute name is the key for each set of values. In addition each map contains the DN as a String * with the key predefined key {@link #DN_KEY}. */ public Set<Map<String, String[]>> searchForMultipleAttributeValues(final String base, final String filter, final Object[] params, final String[] attributeNames) { // Escape the params acording to RFC2254 Object[] encodedParams = new String[params.length]; for (int i = 0; i < params.length; i++) { encodedParams[i] = LdapEncoder.filterEncode(params[i].toString()); } String formattedFilter = MessageFormat.format(filter, encodedParams); logger.debug("Using filter: " + formattedFilter); final HashSet<Map<String, String[]>> set = new HashSet<Map<String, String[]>>(); ContextMapper roleMapper = new ContextMapper() { public Object mapFromContext(Object ctx) { DirContextAdapter adapter = (DirContextAdapter) ctx; Map<String, String[]> record = new HashMap<String, String[]>(); for (String attributeName : attributeNames) { String[] values = adapter.getStringAttributes(attributeName); if (values == null || values.length == 0) { logger.debug("No attribute value found for '" + attributeName + "'"); } else { record.put(attributeName, values); } } record.put(DN_KEY, new String[] { adapter.getDn().toString() }); set.add(record); return null; } }; SearchControls ctls = new SearchControls(); ctls.setSearchScope(searchControls.getSearchScope()); ctls.setReturningAttributes(attributeNames); search(base, formattedFilter, ctls, roleMapper); return set; }
From source file:org.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java
public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException { PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s; if (!config.getBoolean("ldap.bind.authenticator.enabled") || (!config.getBoolean("ldap.bind.authenticator.allowEmptyPasswords", false) && StringUtils.isEmpty(source.getPassword()))) { return new AuthenticationResult(false, source.getPrincipal(), null); }//from www . jav a 2 s . c om SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")" + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute() + "=" + source.getPrincipal() + "))"; log.info("Searching for users with filter: \'{}\'" + " from base dn: {}", filter, mapper.getUserBaseDn()); LdapConnection ldapConnection = getLdapConnection(); LdapConnection authLdapConnection = null; NamingEnumeration<SearchResult> results = null; try { // check the cache for user's userDn in the ldap server String userDn = ldapCacheService.getLdapUserDn(source.getPrincipal()); if (userDn == null) { log.debug("userDn for user {} not found in cache. Retrieving from ldap server..", source.getPrincipal()); DirContext context = ldapConnection.getDirContext(); results = context.search(mapper.getUserBaseDn(), filter, ctls); log.info("Found user?: {}", results.hasMoreElements()); if (results.hasMoreElements()) { SearchResult result = results.nextElement(); userDn = result.getNameInNamespace(); log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getPrincipal()); // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server ldapCacheService.addLdapUserDn(source.getPrincipal(), userDn); } else { return new AuthenticationResult(false, source.getPrincipal(), null); } } log.info("Attempting Authenication: + {}", userDn); authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword()); return new AuthenticationResult(true, source.getPrincipal(), null); } catch (LdapException e) { return new AuthenticationResult(false, source.getPrincipal(), e); } catch (NamingException e) { return new AuthenticationResult(false, source.getPrincipal(), e); } finally { closeNamingEnumeration(results); closeLdapConnection(ldapConnection); if (authLdapConnection != null) { closeLdapConnection(authLdapConnection); } } }
From source file:org.dcm4che3.conf.dicom.ldap.LdapConfigUtils.java
static NamingEnumeration<SearchResult> searchSubcontextWithClass( LdapConfigurationStorage ldapConfigurationStorage, String childObjClass, String dn) throws NamingException { SearchControls ctls = new SearchControls(); ctls.setSearchScope(1); ctls.setReturningObjFlag(false);//from w w w.j av a 2 s .c o m return ldapConfigurationStorage.getLdapCtx().search(dn, "(objectclass=" + childObjClass + ")", ctls); }