List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:org.springframework.security.ldap.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./*from w w w . ja v a2 s . c o m*/ * * @param base the DN to search in * @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, List<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, List<String>>> set = new HashSet<Map<String, List<String>>>(); ContextMapper roleMapper = new ContextMapper() { public Object mapFromContext(Object ctx) { DirContextAdapter adapter = (DirContextAdapter) ctx; Map<String, List<String>> record = new HashMap<String, List<String>>(); if (attributeNames == null || attributeNames.length == 0) { try { for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); extractStringAttributeValues(adapter, record, attr.getID()); } } catch (NamingException x) { org.springframework.ldap.support.LdapUtils.convertLdapException(x); } } else { for (String attributeName : attributeNames) { extractStringAttributeValues(adapter, record, attributeName); } } record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter))); set.add(record); return null; } }; SearchControls ctls = new SearchControls(); ctls.setSearchScope(searchControls.getSearchScope()); ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null); search(base, formattedFilter, ctls, roleMapper); return set; }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void setConfig() throws Throwable { LOG.info("LdapDeltaUserGroupBuilder initialization started"); groupSearchFirstEnabled = config.isGroupSearchFirstEnabled(); userSearchEnabled = config.isUserSearchEnabled(); groupSearchEnabled = config.isGroupSearchEnabled(); ldapUrl = config.getLdapUrl();/* w w w .jav a 2 s . c om*/ ldapBindDn = config.getLdapBindDn(); ldapBindPassword = config.getLdapBindPassword(); //ldapBindPassword = "admin-password"; ldapAuthenticationMechanism = config.getLdapAuthenticationMechanism(); ldapReferral = config.getContextReferral(); searchBase = config.getSearchBase(); userSearchBase = config.getUserSearchBase().split(";"); userSearchScope = config.getUserSearchScope(); userObjectClass = config.getUserObjectClass(); userSearchFilter = config.getUserSearchFilter(); userNameAttribute = config.getUserNameAttribute(); Set<String> userSearchAttributes = new HashSet<String>(); userSearchAttributes.add(userNameAttribute); // For Group based search, user's group name attribute should not be added to the user search attributes if (!groupSearchFirstEnabled && !groupSearchEnabled) { userGroupNameAttributeSet = config.getUserGroupNameAttributeSet(); for (String useGroupNameAttribute : userGroupNameAttributeSet) { userSearchAttributes.add(useGroupNameAttribute); } } userSearchAttributes.add("uSNChanged"); userSearchAttributes.add("modifytimestamp"); userSearchControls = new SearchControls(); userSearchControls.setSearchScope(userSearchScope); userSearchControls .setReturningAttributes(userSearchAttributes.toArray(new String[userSearchAttributes.size()])); pagedResultsEnabled = config.isPagedResultsEnabled(); pagedResultsSize = config.getPagedResultsSize(); groupSearchBase = config.getGroupSearchBase().split(";"); groupSearchScope = config.getGroupSearchScope(); groupObjectClass = config.getGroupObjectClass(); groupSearchFilter = config.getGroupSearchFilter(); groupMemberAttributeName = config.getUserGroupMemberAttributeName(); groupNameAttribute = config.getGroupNameAttribute(); groupHierarchyLevels = config.getGroupHierarchyLevels(); extendedGroupSearchFilter = "(&" + extendedGroupSearchFilter + "(|(" + groupMemberAttributeName + "={0})(" + groupMemberAttributeName + "={1})))"; groupUserMapSyncEnabled = config.isGroupUserMapSyncEnabled(); groupSearchControls = new SearchControls(); groupSearchControls.setSearchScope(groupSearchScope); Set<String> groupSearchAttributes = new HashSet<String>(); groupSearchAttributes.add(groupNameAttribute); groupSearchAttributes.add(groupMemberAttributeName); groupSearchAttributes.add("uSNChanged"); groupSearchAttributes.add("modifytimestamp"); groupSearchControls .setReturningAttributes(groupSearchAttributes.toArray(new String[groupSearchAttributes.size()])); if (LOG.isInfoEnabled()) { LOG.info("LdapDeltaUserGroupBuilder initialization completed with -- " + "ldapUrl: " + ldapUrl + ", ldapBindDn: " + ldapBindDn + ", ldapBindPassword: ***** " + ", ldapAuthenticationMechanism: " + ldapAuthenticationMechanism + ", searchBase: " + searchBase + ", userSearchBase: " + Arrays.toString(userSearchBase) + ", userSearchScope: " + userSearchScope + ", userObjectClass: " + userObjectClass + ", userSearchFilter: " + userSearchFilter + ", extendedUserSearchFilter: " + extendedUserSearchFilter + ", userNameAttribute: " + userNameAttribute + ", userSearchAttributes: " + userSearchAttributes + ", userGroupNameAttributeSet: " + userGroupNameAttributeSet + ", pagedResultsEnabled: " + pagedResultsEnabled + ", pagedResultsSize: " + pagedResultsSize + ", groupSearchEnabled: " + groupSearchEnabled + ", groupSearchBase: " + Arrays.toString(groupSearchBase) + ", groupSearchScope: " + groupSearchScope + ", groupObjectClass: " + groupObjectClass + ", groupSearchFilter: " + groupSearchFilter + ", extendedGroupSearchFilter: " + extendedGroupSearchFilter + ", extendedAllGroupsSearchFilter: " + extendedAllGroupsSearchFilter + ", groupMemberAttributeName: " + groupMemberAttributeName + ", groupNameAttribute: " + groupNameAttribute + ", groupSearchAttributes: " + groupSearchAttributes + ", groupUserMapSyncEnabled: " + groupUserMapSyncEnabled + ", groupSearchFirstEnabled: " + groupSearchFirstEnabled + ", userSearchEnabled: " + userSearchEnabled + ", ldapReferral: " + ldapReferral); } }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static String getOrgDN(String organisation, String countryCode) { NamingEnumeration results = null; DirContext ctx = null;// ww w .ja va 2 s . c o m String dn = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String retAttrs[] = { "dn" }; controls.setReturningAttributes(retAttrs); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search("c=" + countryCode + "," + rb.getString("organisationsRoot"), "(&(objectclass=organization)(o=" + organisation + "))", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); dn = searchResult.getNameInNamespace(); } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return dn; }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
public void updateSchemas() { DirContext dirContext = null; try {/*from w w w .ja v a 2s .c o m*/ dirContext = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); controls.setCountLimit(1); updateSuffix(dirContext); updateGroups(dirContext, controls); updatePeople(dirContext, controls); updateRootDN(dirContext, controls); updateUsers(dirContext, controls); } finally { if (dirContext != null) { try { dirContext.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the LDAP context", ex); } } } }
From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java
public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context) throws NamingException, IOException { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls); final List<LdapUser> users = new ArrayList<LdapUser>(); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); users.add(createUser(result));/*from w w w . j av a 2 s . c om*/ } if (users.size() == 1) { return users.get(0); } else { throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString); } }
From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java
private boolean ldapAuthorizationVerification(String user) { M_log.debug("ldapAuthorizationVerification(): called"); boolean isAuthorized = false; DirContext dirContext = null; NamingEnumeration listOfPeopleInAuthGroup = null; NamingEnumeration allSearchResultAttributes = null; NamingEnumeration simpleListOfPeople = null; Hashtable<String, String> env = new Hashtable<String, String>(); if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) { env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY); env.put(Context.PROVIDER_URL, providerURL); } else {/* w ww .ja v a 2 s. co m*/ M_log.error( " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file"); return isAuthorized; } try { dirContext = new InitialDirContext(env); String[] attrIDs = { "member" }; SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(attrIDs); searchControls.setReturningObjFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBase = OU_GROUPS; String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))"; listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls); String positiveMatch = "uid=" + user + ","; outerloop: while (listOfPeopleInAuthGroup.hasMore()) { SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next(); allSearchResultAttributes = (searchResults.getAttributes()).getAll(); while (allSearchResultAttributes.hasMoreElements()) { Attribute attr = (Attribute) allSearchResultAttributes.nextElement(); simpleListOfPeople = attr.getAll(); while (simpleListOfPeople.hasMoreElements()) { String val = (String) simpleListOfPeople.nextElement(); if (val.indexOf(positiveMatch) != -1) { isAuthorized = true; break outerloop; } } } } return isAuthorized; } catch (NamingException e) { M_log.error("Problem getting attribute:" + e); return isAuthorized; } finally { try { if (simpleListOfPeople != null) { simpleListOfPeople.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ", e); } try { if (allSearchResultAttributes != null) { allSearchResultAttributes.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ", e); } try { if (listOfPeopleInAuthGroup != null) { listOfPeopleInAuthGroup.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ", e); } try { if (dirContext != null) { dirContext.close(); } } catch (NamingException e) { M_log.error("Problem occurred while closing the \"dirContext\" object", e); } } }
From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java
/** * @param dn the distinguished name of the entry - may be either relative to the base * context or a complete DN including the name of the context (either is * supported)./* w w w .jav a2s.c o m*/ * @param username the user whose roles are required. * @return the granted authorities returned by the group search */ @SuppressWarnings("unchecked") List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) { SearchExecutor se = new SearchExecutor() { public NamingEnumeration<SearchResult> executeSearch(DirContext ctx) throws NamingException { DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx); SearchControls ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] { groupRoleAttributeName }); return ctx.search(groupSearchBase, groupSearchFilter, new String[] { fullDn.toUrl(), username }, ctrls); } }; AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(roleMapper); template.search(se, roleCollector); return roleCollector.getList(); }
From source file:no.smint.anthropos.ldap.LDAP.java
public static String getDn(String uid) throws NamingException { Hashtable<String, Object> env = config(); DirContext ctx = new InitialDirContext(env); SearchControls ctls = new SearchControls(); String filter = ("uid=" + uid); NamingEnumeration answer = ctx.search(name, filter, ctls); SearchResult searchResult;/*w w w . ja v a 2 s .c o m*/ if (answer.hasMoreElements()) { searchResult = (SearchResult) answer.next(); } else { System.out.println("Found no user by that name"); return null; } if (answer.hasMoreElements()) { System.err.println("Matched mutliple users for the uid" + uid); return null; } ctx.close(); return searchResult.getNameInNamespace(); }
From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java
/** * Search for all users starting at <code>ou=groups</code>, looking for objects with * <code>objectClass=groupOfUniqueNames</code>, and extracting the <code>uid</code> token of the * <code>uniqueMember</code> attribute. *///w w w . j a v a2 s . com @Test public void testGetAllUserNames1() throws Exception { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$ LdapSearchParamsFactoryImpl paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$ "(objectClass=groupOfUniqueNames)", con1); //$NON-NLS-1$ paramFactory.afterPropertiesSet(); Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$ GenericLdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1); allUsernamesSearch.afterPropertiesSet(); DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService(); userRoleListService.setAllUsernamesSearch(allUsernamesSearch); List res = userRoleListService.getAllUsers(); assertTrue(res.contains("pat")); //$NON-NLS-1$ assertTrue(res.contains("admin")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllUserNames1(): " + res); //$NON-NLS-1$ } }
From source file:org.apache.zeppelin.server.ActiveDirectoryGroupRealm.java
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException { Set<String> roleNames = new LinkedHashSet<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String userPrincipalName = username; if (principalSuffix != null) { userPrincipalName += principalSuffix; }// w w w .j ava 2s . c o m String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))"; Object[] searchArguments = new Object[] { userPrincipalName }; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving group names for user [" + sr.getName() + "]"); } Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().equals("memberOf")) { Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr); if (log.isDebugEnabled()) { log.debug("Groups found for user [" + username + "]: " + groupNames); } Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames); roleNames.addAll(rolesForGroups); } } } } return roleNames; }