List of usage examples for javax.naming.directory DirContext search
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException;
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser findUserByMail(String mail) { NamingEnumeration results = null; DirContext ctx = null; LDAPUser user = null;/*w w w .j ava 2 s.co m*/ try { ctx = getContext(); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user = getUser((String) attributes.get("cn").get()); } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(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 user; }
From source file:com.surevine.chat.auth.GroupAuthorisationFilter.java
/** * Get a list of the members of a group, searching for the group using an * LDAP filter expression and scope./* www . ja v a 2 s . co m*/ * * @param filter * LDAP search filter (see RFC2254) * @param scope * One of SearchControls.OBJECT_SCOPE, * SearchControls.ONELEVEL_SCOPE, or SearchControls.SUBTREE_SCOPE * (see javax.naming.directory.SearchControls) * @return List of usernames * @throws NamingException * @throws LdapException * On any LDAP error */ private Collection<String> getGroupMembers(final String groupName) throws NamingException { _logger.debug("Looking for members of " + groupName); String filter = "cn=" + groupName; Collection<String> memberList = new HashSet<String>(20); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> objects; DirContext ctx = getLdapConnection(); objects = ctx.search("ou=groups", filter, controls); while (objects.hasMore()) { SearchResult sr = (SearchResult) objects.next(); Attributes attributes = sr.getAttributes(); Attribute attribute = attributes.get("member"); if (attribute != null) { NamingEnumeration<?> valueEnum = attribute.getAll(); while (valueEnum.hasMore()) { String value = valueEnum.next().toString(); final String searchFor = "cn="; int start = value.indexOf(searchFor); int end = value.indexOf(',', start); if (start >= 0 && end >= 0) { String name = value.substring(start + searchFor.length(), end); _logger.debug(name + " is a chatter"); memberList.add(name); } } } } _logger.debug("Returning a total of " + memberList.size() + " chatters"); return memberList; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getUser(String cn) { LDAPUser user = null;/*from w w w.j a va 2 s. c o m*/ NamingEnumeration results = null; DirContext ctx = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } 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 user; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getIfValidUser(String cn, String password) { LDAPUser user = null;//from w ww. j a v a 2 s . com NamingEnumeration results = null; DirContext ctx = null; try { ctx = getAuthContext(cn, password); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } 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 user; }
From source file:org.apache.archiva.redback.authentication.ldap.LdapBindAuthenticator.java
public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException { PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s; if (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ENABLED) || (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false) && StringUtils.isEmpty(source.getPassword()))) { return new AuthenticationResult(false, source.getUsername(), null); }/*from www . j a v 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.getUsername() + "))"; log.debug("Searching for users with filter: '{}' from base dn: {}", filter, mapper.getUserBaseDn()); LdapConnection ldapConnection = null; LdapConnection authLdapConnection = null; NamingEnumeration<SearchResult> results = null; try { ldapConnection = getLdapConnection(); // check the cache for user's userDn in the ldap server String userDn = ldapCacheService.getLdapUserDn(source.getUsername()); if (userDn == null) { log.debug("userDn for user {} not found in cache. Retrieving from ldap server..", source.getUsername()); DirContext context = ldapConnection.getDirContext(); results = context.search(mapper.getUserBaseDn(), filter, ctls); log.debug("Found user '{}': {}", source.getUsername(), results.hasMoreElements()); if (results.hasMoreElements()) { SearchResult result = results.nextElement(); userDn = result.getNameInNamespace(); log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getUsername()); // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server ldapCacheService.addLdapUserDn(source.getUsername(), userDn); } else { return new AuthenticationResult(false, source.getUsername(), null); } } log.debug("Attempting Authenication: {}", userDn); authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword()); log.info("user '{}' authenticated", source.getUsername()); return new AuthenticationResult(true, source.getUsername(), null); } catch (LdapException e) { return new AuthenticationResult(false, source.getUsername(), e); } catch (NamingException e) { return new AuthenticationResult(false, source.getUsername(), e); } finally { closeNamingEnumeration(results); closeLdapConnection(ldapConnection); if (authLdapConnection != null) { closeLdapConnection(authLdapConnection); } } }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static List<Organization> getOrgList(String country) { List<Organization> OrgList = new ArrayList<Organization>(); NamingEnumeration resultCountries = null; DirContext ctx = null; try {//from www . j a v a2 s . c o m ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); String filter; if (country == null) { filter = "(objectclass=country)"; } else { filter = "(&(objectclass=country)(c=" + country + "))"; } resultCountries = ctx.search(rb.getString("organisationsRoot"), filter, controls); while (resultCountries.hasMore()) { SearchResult searchResult = (SearchResult) resultCountries.next(); Attributes attributes = searchResult.getAttributes(); String countryCode = (String) attributes.get("c").get(); String countryName = (String) attributes.get("co").get(); NamingEnumeration resultsOrgs = ctx.search( "c=" + countryCode + "," + rb.getString("organisationsRoot"), "(objectclass=organization)", controls); while (resultsOrgs.hasMore()) { SearchResult srOrg = (SearchResult) resultsOrgs.next(); Attributes orgAttrs = srOrg.getAttributes(); String description = ""; if ((orgAttrs.get("description")) != null) { description = (String) orgAttrs.get("description").get(); } OrgList.add(new Organization((String) orgAttrs.get("o").get(), countryName, countryCode, description, srOrg.getNameInNamespace())); } resultsOrgs.close(); } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { throw new RuntimeException(e); } finally { if (resultCountries != null) { try { resultCountries.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } Collections.sort(OrgList, new Comparator<Organization>() { public int compare(Organization o1, Organization o2) { return o1.getKey().compareTo(o2.getKey()); } }); return OrgList; }
From source file:org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler.java
protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials) throws AuthenticationException { final List<String> cns = new ArrayList<String>(); final SearchControls searchControls = getSearchControls(); final String base = this.searchBase; final String transformedUsername = getPrincipalNameTransformer().transform(credentials.getUsername()); final String filter = LdapUtils.getFilterWithValues(getFilter(), transformedUsername); this.getLdapTemplate().search(new SearchExecutor() { public NamingEnumeration executeSearch(final DirContext context) throws NamingException { return context.search(base, filter, searchControls); }/*from ww w .j a v a 2s.c om*/ }, new NameClassPairCallbackHandler() { public void handleNameClassPair(final NameClassPair nameClassPair) { cns.add(nameClassPair.getNameInNamespace()); } }); if (cns.isEmpty()) { log.info("Search for " + filter + " returned 0 results."); return false; } if (cns.size() > 1 && !this.allowMultipleAccounts) { log.warn("Search for " + filter + " returned multiple results, which is not allowed."); return false; } for (final String dn : cns) { DirContext test = null; String finalDn = composeCompleteDnToCheck(dn, credentials); try { this.log.debug("Performing LDAP bind with credential: " + dn); test = this.getContextSource().getContext(finalDn, getPasswordEncoder().encode(credentials.getPassword())); if (test != null) { return true; } } catch (final Exception e) { if (this.log.isErrorEnabled()) this.log.error(e.getMessage(), e); throw handleLdapError(e); } finally { LdapUtils.closeContext(test); } } return false; }
From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java
/** * Ensure able to obtain credentials./*from w w w .jav a 2s . com*/ */ public void testObtainCredentials() throws Exception { final Charset ASCII = Charset.forName("ASCII"); // Calculate the expected credential String expectedRaw = "daniel:officefloor:password"; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(expectedRaw.getBytes(ASCII)); byte[] expectedBytes = digest.digest(); String expectedCredentials = Base64.encodeBase64String(expectedBytes).trim(); // Obtain the context DirContext context = this.ldap.getDirContext(); // Obtain the People context DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net"); assertNotNull("Should have People context", people); // Search for person NamingEnumeration<SearchResult> results = people.search("", "(&(objectClass=inetOrgPerson)(uid=daniel))", null); assertTrue("Expecting to find daniel entry", results.hasMore()); SearchResult result = results.next(); assertFalse("Should only have the daniel entry", results.hasMore()); // Obtain the digest MD5 credentials for Daniel String digestMd5Credential = null; Attributes attributes = result.getAttributes(); Attribute passwordAttribute = attributes.get("userPassword"); for (NamingEnumeration<?> enumeration = passwordAttribute.getAll(); enumeration.hasMore();) { byte[] credentials = (byte[]) enumeration.next(); String text = new String(credentials, ASCII); // Determine if MD5 credential if (text.toUpperCase().startsWith("{MD5}")) { // Found MD5 credential digestMd5Credential = text.substring("{MD5}".length()); } } assertNotNull("Must have digest MD5 credential", digestMd5Credential); // Ensure correct credentials assertEquals("Incorrect DIGEST MD5 credentials", expectedCredentials, digestMd5Credential); }
From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java
/** * Ensure able to obtain the roles.// w w w.j av a 2s . c o m */ public void testObtainRoles() throws Exception { // Obtain the context DirContext context = this.ldap.getDirContext(); // Obtain the People context DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net"); assertNotNull("Should have People context", people); // Search for person NamingEnumeration<SearchResult> personResults = people.search("", "(&(objectClass=inetOrgPerson)(uid=daniel))", null); assertTrue("Expecting to find daniel entry", personResults.hasMore()); SearchResult daniel = personResults.next(); assertFalse("Should only have the daniel entry", personResults.hasMore()); // Obtain the Groups context DirContext groups = (DirContext) context.lookup("ou=Groups,dc=officefloor,dc=net"); assertNotNull("Should have Groups context", groups); // Search for groups containing daniel String danielDn = daniel.getNameInNamespace(); NamingEnumeration<SearchResult> groupResults = groups.search("", "(&(objectClass=groupOfNames)(member=" + danielDn + "))", null); // Obtain the listing of roles for daniel List<String> roles = new ArrayList<String>(2); for (; groupResults.hasMore();) { SearchResult group = groupResults.next(); // Obtain the role from the group String role = (String) group.getAttributes().get("ou").get(); // Add role to listing roles.add(role); } // Ensure the correct roles assertEquals("Incorrect number of roles", 2, roles.size()); assertTrue("Missing user role", roles.contains("developer")); assertTrue("Missing developer role", roles.contains("committer")); }
From source file:com.seyren.core.security.ldap.LdapUserManagement.java
@Override public String[] autoCompleteUsers(String name) { List<String> users = new ArrayList<String>(); try {/*from w ww .j a v a 2s . co m*/ DirContext readOnlyContext = contextSource.getReadOnlyContext(); SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = { USERNAME }; ctls.setReturningAttributes(attrIDs); NamingEnumeration<SearchResult> results = readOnlyContext.search("", "(sAMAccountName=" + name + "*)", ctls); while (results.hasMore()) { SearchResult rslt = results.next(); Attributes attrs = rslt.getAttributes(); if (attrs.get(USERNAME) != null) { users.add((String) attrs.get(USERNAME).get()); } } } catch (NamingException e) { } return users.toArray(new String[users.size()]); }