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:io.apiman.tools.ldap.ApimanLdapServer.java
@Test public void startLdapServer() throws Exception { DirContext ctx = createContext(); Assert.assertNotNull(ctx);//from w w w . ja v a2s. c o m SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls); int count = 0; while (result.hasMore()) { result.next(); count++; } String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort(); System.out.println("======================================================"); System.out.println("LDAP server started successfully."); System.out.println(""); System.out.println(" URL: " + url); System.out.println(" Node Count: " + count); System.out.println(" Direct Bind DN: cn=${username},ou=developers,ou=people,o=apiman"); System.out.println("======================================================"); System.out.println(""); System.out.println(""); System.out.println("Press Enter to stop the LDAP server."); new BufferedReader(new InputStreamReader(System.in)).readLine(); System.out.println("Shutting down the LDAP server..."); }
From source file:egovframework.com.ext.ldapumt.service.impl.DeptManageLdapDAO.java
/** * ?.//from ww w .j av a2s .co m * @param vo vo */ public boolean hasChildren(String dn) throws NamingException { ContextSource contextSource = ldapTemplate.getContextSource(); DirContext ctx = contextSource.getReadOnlyContext(); String filter = "objectclass=*"; SearchControls control = new SearchControls(); control.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> n = ctx.search(dn, filter, control); if (n != null && n.hasMore()) { return true; } return false; }
From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java
@Test @Ignore/* w ww . j a v a 2 s . c o m*/ public void testLdap() throws Exception { DirContext ctx = createContext(); Assert.assertNotNull(ctx); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls); System.out.println(" ==== Search Results ===="); while (result.hasMore()) { SearchResult entry = result.next(); System.out.println(" ===> " + entry.getName()); } }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Retrieves a list of all the groups in the directory. * @param dirContext a DirContext/*from w w w.j a v a 2 s . co m*/ * @return A list of Strings representing the fully qualified DN of each group * @throws NamingException if an exception if thrown * @since 1.4.0 */ public List<String> getGroups(DirContext dirContext) throws NamingException { final List<String> groupDns = new ArrayList<>(); final SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, GROUPS_FILTER, sc); while (hasMoreEnum(ne)) { final SearchResult result = ne.next(); groupDns.add(result.getNameInNamespace()); } closeQuietly(ne); return groupDns; }
From source file:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java
@Override public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;/*w w w. j ava 2 s .c o m*/ Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (StringUtils.isEmpty(password)) { LOG.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } // If DN patterns are configured, try authenticating with them directly for (String dn : getUserDns(username)) { user = bindWithDn(dn, username, password); if (user != null) { break; } } // Otherwise use the configured search object to find the user and authenticate with the returned DN. if (user == null && getUserSearch() != null) { DirContextOperations userFromSearch = getUserSearch().searchForUser(username); user = bindWithDn(userFromSearch.getDn().toString(), username, password); } try { if (user != null && StringUtils.isNotEmpty(gizmoGroup)) { BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource(); DirContext ctx = ctxSource.getReadOnlyContext(); DistinguishedName userDn = new DistinguishedName(user.getDn()); userDn.prepend(ctxSource.getBaseLdapPath()); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = String.format(GROUP_SEARCH_QUERY, gizmoGroup, userDn.toCompactString()); NamingEnumeration en = ctx.search("", filter, controls); if (!en.hasMore()) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } } } catch (javax.naming.NamingException ex) { throw new BadCredentialsException("Couldn't check group membership"); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Retrieves a list of all groups the user is a member of. * @param dirContext a DirContext/*from w ww . j ava 2 s . c o m*/ * @param ldapUser the LdapUser to retrieve group membership for * @return A list of Strings representing the fully qualified DN of each group * @throws NamingException if an exception is thrown * @since 1.4.0 */ public List<String> getGroups(DirContext dirContext, LdapUser ldapUser) throws NamingException { final List<String> groupDns = new ArrayList<>(); final String searchFilter = variableSubstitution(USER_GROUPS_FILTER, ldapUser); final SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, searchFilter, sc); while (hasMoreEnum(ne)) { final SearchResult result = ne.next(); groupDns.add(result.getNameInNamespace()); } closeQuietly(ne); return groupDns; }
From source file:com.hs.mail.security.login.JndiLoginModule.java
@SuppressWarnings("unchecked") protected boolean authenticate(String username, String password) throws Exception { DirContext context = null; try {//from w w w. j a va 2 s . co m context = open(); searchFilterFormat.format(new String[] { username }); SearchControls constraints = new SearchControls(); constraints.setSearchScope(subtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE); if (returnAttribute != null) { String[] attribs = StringUtils.split(returnAttribute, ","); constraints.setReturningAttributes(attribs); } NamingEnumeration ne = context.search(base, searchFilter, constraints); if (ne == null || !ne.hasMore()) { return false; } SearchResult sr = (SearchResult) ne.next(); if (ne.hasMore()) { // Ignore for now } // Check the credentials by binding to server if (bindUser(context, sr.getNameInNamespace(), password)) { return true; } else { return true; } } catch (NamingException e) { close(context); return false; } }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Performs a search for the specified username. Internally, this method queries on * the attribute defined by {@link Config.AlpineKey#LDAP_ATTRIBUTE_NAME}. * @param ctx the DirContext to use/*w ww .j a va 2s . c o m*/ * @param username the username to query on * @return a list of SearchResult objects. If the username is found, the list should typically only contain one result. * @throws NamingException if an exception is thrown * @since 1.4.0 */ public List<SearchResult> searchForUsername(DirContext ctx, String username) throws NamingException { final String[] attributeFilter = {}; final SearchControls sc = new SearchControls(); sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); final String searchFor = LdapConnectionWrapper.ATTRIBUTE_NAME + "=" + LdapStringSanitizer.sanitize(formatPrincipal(username)); return Collections.list(ctx.search(LdapConnectionWrapper.BASE_DN, searchFor, sc)); }
From source file:com.aurel.track.util.LdapUtil.java
/** * Returns the CN (common name) for a given login name * //from w w w. ja va2 s . c o m * @param loginName * the loginName of the user * @return CN as a String(if found), or null (else) */ private static String getCn(TSiteBean siteBean, String loginName) throws NamingException { String keyDn = null; DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(), siteBean.getLdapBindPassword()); if (ctx != null) { SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search for the user-id String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")"; NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls); if (answer.hasMore()) { // retrieve the CN SearchResult sr = answer.next(); keyDn = sr.getName();// + "," + ctx.getNameInNamespace(); LOGGER.debug("Name = " + keyDn); String nameInNamespace = ctx.getNameInNamespace(); LOGGER.debug("Name in namespace " + nameInNamespace); if (nameInNamespace != null && nameInNamespace.trim().length() > 0) { keyDn += "," + ctx.getNameInNamespace(); } LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!"); answer.close(); // wo don't need more answers } else { LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!"); } ctx.close(); } return keyDn; }
From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java
private User getUser(Credentials credentials, DirContext ctx) throws PhrescoException { if (isDebugEnabled) { S_LOGGER.debug("Entering Method LDAPManagerImpl.getUserInfo(String userName, DirContext ctx)"); }// w w w . jav a2 s.co m User user = new User(); try { String userName = credentials.getUsername(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = { "*" }; constraints.setReturningAttributes(attrIDs); NamingEnumeration<SearchResult> ne = ctx.search(ldapConfig.getLdapBaseDn(), ldapConfig.getLdapLoginAttribute() + Constants.STR_EQUALS + userName, constraints); if (ne.hasMore()) { Attributes attrs = ne.next().getAttributes(); user.setName(userName); // userInfo.setCredentials(credentials); user.setDisplayName(getDisplayName(attrs)); user.setEmail(getMailId(attrs)); user.setPhrescoEnabled(isPhrescoEnabled(attrs)); // userInfo.setCustomerNames(getCustomerNames(attrs)); } } catch (Exception e) { throw new PhrescoException(e); } return user; }