List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java
@Override public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;/*from w w w . j av a 2 s. c om*/ 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:com.hs.mail.security.login.JndiLoginModule.java
@SuppressWarnings("unchecked") protected boolean authenticate(String username, String password) throws Exception { DirContext context = null;//from w w w . j a v a 2 s. c o m try { 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:io.apiman.tools.ldap.ApimanLdapServer.java
@Test public void startLdapServer() throws Exception { DirContext ctx = createContext(); Assert.assertNotNull(ctx);/*from w w w . java2 s . co 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:com.adito.activedirectory.PagedResultTemplate.java
boolean searchForResult(InitialLdapContext context, String searchBase, String filter) throws NamingException { SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints); return results.hasMore(); }
From source file:se.inera.axel.shs.broker.directory.internal.LdapDirectoryService.java
/** * Finds all entries matching filter, mapped with the mapper. * If organization is given, it is used as a search base. * For instance: list all addresses under a given organization. * * At most 'limit' entries are returned. * * @param organization/*from www .ja v a2s.c o m*/ * @param filter * @param mapper * @param limit * @param dirContextProcessor * @param <T> * @return * @throws DirectoryException */ private <T> List<T> findAll(Organization organization, AndFilter filter, ParameterizedContextMapper<T> mapper, long limit, DirContextProcessor dirContextProcessor) throws DirectoryException { List<T> entries = new ArrayList<T>(); String base = ""; try { SearchControls ctrl = new SearchControls(); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setReturningObjFlag(true); ctrl.setCountLimit(limit); if (organization != null) { base = "o=" + organization.getOrgName(); } entries = ldapTemplate.search(base, filter.encode(), ctrl, mapper, dirContextProcessor); // Remove duplicates... HashSet<T> set = new HashSet<T>(entries); entries = new ArrayList<T>(set); } catch (NameNotFoundException e) { log.warn("not found in ldap directory: " + base + "," + filter.encode()); } catch (RuntimeException e) { log.error("error during looking-up", e); throw new DirectoryException("error during looking-up", e); } return entries; }
From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java
public String searchQueryLDAP() { NamingEnumeration results = null; ObjectMapper mapper = new ObjectMapper(); Response response;/*from w ww . j a v a 2 s.com*/ String resultOutput = new String(); List<Map<String, String>> attributesList = new LinkedList<>(); String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES)); try { ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL), allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME), allLDAPClientParameters.get(ARG_PASSWORD)); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (attributesToReturn.length > 0) { controls.setReturningAttributes(attributesToReturn); } results = ldapConnection.search( getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_SEARCH_BASE)), allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls); // Iterate through all attributes in the result of search query while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); if (attributes != null && attributes.size() > 0) { NamingEnumeration ae = attributes.getAll(); Map<String, String> attributesMap = new HashMap<>(); while (ae.hasMore()) { Attribute attribute = (Attribute) ae.next(); attributesMap.put(attribute.getID(), attribute.get().toString()); } attributesList.add(attributesMap); } } response = new LDAPResponse("Ok", attributesList); } catch (Exception e) { response = new ErrorResponse("Error", e.toString()); } finally { if (results != null) { try { results.close(); } catch (Exception e) { e.printStackTrace(); } } if (ldapConnection != null) { try { ldapConnection.close(); } catch (Exception e) { e.printStackTrace(); } } } try { resultOutput = mapper.writeValueAsString(response); } catch (JsonProcessingException e) { e.printStackTrace(); } return resultOutput; }
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)"); }/*from w w w . jav a 2 s. c o 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; }
From source file:com.adito.activedirectory.PagedResultTemplate.java
private void doSearch(InitialLdapContext context, String filter, String[] attributes, PagedResultMapper mapper) throws NamingException { SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); for (String searchBase : ouSearchBase) { if (logger.isDebugEnabled()) { logger.debug("Looking for items starting at " + searchBase + " (filter = " + filter + ")"); }//w w w .j a va 2s. c om try { constraints.setReturningAttributes(attributes); NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints); mapResults(mapper, results); } catch (PartialResultException e) { // ignore } catch (NamingException e) { mapper.processException(e); logger.error("Possible configuration error! Did you enter your OUs correctly? [" + searchBase + "]", e); } } }
From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchGroupResolver.java
/** * Resolves groups by querying the LDAP directory. * /*from w ww .j a v a 2 s . c om*/ * Never return null in any case. Returns empty list instead. * * @param ctx * @param dn * @param username * @return List of authorities (not null) * @see jp.ikedam.jenkins.plugins.ldap_sasl.GroupResolver#resolveGroup(javax.naming.ldap.LdapContext, java.lang.String, java.lang.String) */ @Override public List<GrantedAuthority> resolveGroup(LdapContext ctx, String dn, String username) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); Logger logger = getLogger(); if (dn == null) { logger.warning("Group cannot be resolved: DN of the user is not resolved!"); return authorities; } try { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); logger.fine(String.format("Searching groups base=%s, dn=%s", getSearchBase(), dn)); NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "", getGroupSearchQuery(dn), searchControls); while (entries.hasMore()) { SearchResult entry = entries.next(); String groupName = entry.getAttributes().get("cn").get().toString(); if (getPrefix() != null) { groupName = getPrefix() + groupName; } authorities.add(new GrantedAuthorityImpl(groupName)); logger.fine(String.format("group: %s", groupName)); } entries.close(); } catch (NamingException e) { logger.log(Level.WARNING, "Failed to search groups", e); } return authorities; }
From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java
/** * displayName and mail are returned always, the map allows us to support * getting arbitrary properties in the future, hopefully *//*from ww w. ja va2 s .co m*/ public Map<String, String> bind(String loginName, String password) throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); LdapContext ctx = null; if (activeDirectoryDomain != null) { // we are using Active Directory Control[] controls = new Control[] { control }; ctx = new InitialLdapContext(env, controls); logger.debug("Active Directory LDAP context initialized"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); // javax.naming.AuthenticationException ctx.reconnect(controls); logger.debug("Active Directory LDAP bind successful"); } else { // standard LDAP env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase); env.put(Context.SECURITY_CREDENTIALS, password); ctx = new InitialLdapContext(env, null); logger.debug("Standard LDAP bind successful"); } SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(returningAttributes); NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc); while (results.hasMoreElements()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); logger.debug("attributes: " + attrs); Map<String, String> map = new HashMap<String, String>(returningAttributes.length); for (String key : returningAttributes) { Attribute attr = attrs.get(key); if (attr != null) { map.put(key, (String) attr.get()); } } return map; // there should be only one anyway } // if we reached here, there was no search result throw new Exception("no results returned from ldap"); }