List of usage examples for javax.naming.ldap InitialLdapContext search
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException
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:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java
public AuthenticationResult validate(AuthMethod authMethod, Authentication authentication, TransactionData transactionData) { LdapAuthMethod ldapAuthMethod = (LdapAuthMethod) authMethod; UserPasswordAuthentication userPwAuthentication = (UserPasswordAuthentication) authentication; boolean validation; String userId = userPwAuthentication.getUserId(); String password = userPwAuthentication.getPassword(); GenericObjectPool<InitialLdapContext> pool = pools.get(authMethod.getName()); InitialLdapContext ctx = null; try {/*from www.jav a2s.c o m*/ ctx = pool.borrowObject(); // First we search the user SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = ldapAuthMethod.getUserSearchFilter().replace("#UID", SecurityUtils.escapeLDAPSearchFilter(userId)); NamingEnumeration<SearchResult> results = ctx.search(ldapAuthMethod.getBaseDn(), searchFilter, controls); SearchResult result; if (results.hasMoreElements()) { result = results.next(); if (results.hasMoreElements()) { LOG.error("User ID {} is not unique in LDAP {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.USER_NOT_UNIQUE); } } else { LOG.error("User ID {} does not exist in LDAP {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS); } // Try to bind with the found user id validation = ((LdapConnectionFactory) pool.getFactory()).authenticate(authMethod.getName(), result.getNameInNamespace(), password); pool.returnObject(ctx); if (validation) { LOG.info("User {} successfully authenticated with {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.SUCCESS).setUserId(userId) .setAuthMethod(authMethod).setAuthLevel(authMethod.getAuthLevel()); } else { LOG.error("Authentication failed for user {} with {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS); } } catch (Exception ex) { // Discard context try { if (ctx != null) { pool.invalidateObject(ctx); } } catch (Exception ex2) { LOG.error("An error occurend when authenticating user"); } return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.TECHNICAL_ERROR); } }
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 + ")"); }//from ww w . j av a 2 s . 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:com.adito.activedirectory.PagedResultTemplate.java
private void doPagedSearch(InitialLdapContext context, String filter, String[] attributes, PagedResultMapper mapper) throws NamingException { SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); applyControls(context, pageSize);/*from ww w . j av a 2 s .c o m*/ for (String searchBase : ouSearchBase) { if (logger.isDebugEnabled()) { logger.debug("Looking for items starting at " + searchBase + " (filter = " + filter + ")"); } try { int currentPage = 1; int startPosition = 0; int endPosition = pageSize - 1; byte[] cookie = null; do { String range = startPosition + "-" + endPosition; if (logger.isDebugEnabled()) { logger.debug("Starting search on page " + currentPage + " " + range); } constraints.setReturningAttributes(attributes); NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints); try { mapResults(mapper, results); } catch (PartialResultException pre) { // We're paging so we dont care and don't log anymore } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int index = 0; index < controls.length; index++) { if (controls[index] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[index]; cookie = prrc.getCookie(); } } } applyControls(context, pageSize, cookie); startPosition = startPosition + pageSize; endPosition = endPosition + pageSize; currentPage++; } while ((cookie != null) && (cookie.length != 0)); } catch (NamingException e) { mapper.processException(e); logger.error("Possible configuration error! Did you enter your OUs correctly? [" + searchBase + "]", e); } } }
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Does a subtree search for an element given a pattern. Only the first * element found is considered, and all references are searched in order * until either a match is found or no more references are left to search. * @param ldap// w ww . jav a 2 s. c om * A prepared LDAP context. * @param pattern * The search pattern. Must not include the character '*' or the * substring '\2a' to prevent possible LDAP exploits. * @return The element's relative DN, or <code>null</code> if none was * found. <code>null</code> is also returned if the search pattern * contains an illegal character or substring. * @throws BackendException * If there was a problem accessing the backend. Typical causes * include timeouts. */ private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException { // Check pattern for illegal content. String[] illegals = { "*", "\\2a" }; for (int i = 0; i < illegals.length; i++) { if (pattern.indexOf(illegals[i]) > -1) return null; } // The context provider URL, for later logging. String url = "unknown backend"; // Start counting the (milli)seconds and prepare for timeouts. long searchStart = System.currentTimeMillis(); JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket); NamingEnumeration results; try { // Remember the URL, for later logging. url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL); interruptTask.setURL(url); // Start timeout interruptor and perform the search. Timer interruptTimer = new Timer(); interruptTimer.schedule(interruptTask, (1000 * myTimeout)); results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout, new String[] {}, false, false)); interruptTimer.cancel(); if (!results.hasMore()) return null; } catch (TimeLimitExceededException e) { // The search timed out. log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket); return null; } catch (SizeLimitExceededException e) { // The search returned too many results. log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket); return null; } catch (NameNotFoundException e) { // Element not found. Possibly non-existing reference. log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary? return null; } catch (AuthenticationException e) { // Search failed authentication; check non-anonymous search config. try { final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL); final String errorMessage; if ((searchUser == null) || searchUser.equals("")) errorMessage = "Anonymous search failed authentication on " + url; else errorMessage = "Could not authenticate search user " + searchUser + " on " + url; log.logDebug(errorMessage, mySessionTicket); throw new BackendException(errorMessage, e); } catch (NamingException f) { // Should not happen! log.logCritical("Unable to read LDAP environment", mySessionTicket, f); throw new BackendException("Unable to read LDAP environment", f); } } catch (NamingException e) { // Did we interrupt the search ourselves? if (interruptTask.finished()) { final long elapsed = System.currentTimeMillis() - searchStart; log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms", mySessionTicket); throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms; connection terminated"); } // All other exceptions. log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e); return null; } // We just found at least one element. Did we get an ambigious result? SearchResult entry = null; try { entry = (SearchResult) results.next(); String buffer = new String(); while (results.hasMoreElements()) buffer = buffer + ", " + ((SearchResult) results.next()).getName(); if (!buffer.equals("")) log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName() + buffer + "]", mySessionTicket); // TODO: Throw BackendException, or a subclass, or just (as now) // pick the first and hope for the best? buffer = null; } catch (NamingException e) { throw new BackendException("Unable to read search results", e); } return entry.getName(); // Relative DN (to the reference). }
From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java
/** * Find account by account name.//w w w.j a v a 2s .co m * * @param accountName the account name * @return the search result * @throws NamingException the naming exception */ protected SearchResult findAccountByAccountName(String accountName) throws NamingException { String searchFilter = String.format(searchFilterPattern, accountName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); InitialLdapContext ctx = new InitialLdapContext(env, null); try { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls); if (!results.hasMoreElements()) { throw new UserConfigLoaderException("LDAP Search returned no accounts"); } SearchResult searchResult = results.nextElement(); if (results.hasMoreElements()) { throw new UserConfigLoaderException("More than one account found in ldap search"); } return searchResult; } finally { ctx.close(); } }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Obtains the roles for the given user. * * @param username the user name to fetch user data. * @return the list of roles to which the user is associated to. * @throws NamingException LDAP error obtaining roles fro the given user *//* w w w. java2 s.c o m*/ protected String[] selectRolesByUsername(String username) throws NamingException, NoSuchUserException { List userRoles = new ArrayList(); InitialLdapContext ctx = createLdapInitialContext(); String rolesCtxDN = getRolesCtxDN(); // Search for any roles associated with the user if (rolesCtxDN != null) { // The attribute where user DN is stored in roles : String uidAttributeID = getUidAttributeID(); if (uidAttributeID == null) uidAttributeID = "uniquemember"; // The attribute that identifies the role name String roleAttrName = getRoleAttributeID(); if (roleAttrName == null) roleAttrName = "roles"; String userDN; if ("UID".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = username; } else if ("PRINCIPAL".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = _principalUidAttributeID + "=" + username; } else { // Default behaviour: Match the role using the User DN, not just the username : userDN = selectUserDN(username); } if (logger.isDebugEnabled()) logger.debug( "Searching Roles for user '" + userDN + "' in Uid attribute name '" + uidAttributeID + "'"); if (userDN == null) throw new NoSuchUserException(username); try { if (userDN.contains("\\")) { logger.debug("Escaping '\\' character"); userDN = userDN.replace("\\", "\\\\\\"); } NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))", getSearchControls()); if (logger.isDebugEnabled()) logger.debug("Search Name: " + rolesCtxDN); if (logger.isDebugEnabled()) logger.debug("Search Filter: (&(" + uidAttributeID + "=" + userDN + "))"); if (!answer.hasMore()) logger.info("No roles found for user " + username); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute roles = attrs.get(roleAttrName); for (int r = 0; r < roles.size(); r++) { Object value = roles.get(r); String roleName = null; // The role attribute value is the role name roleName = value.toString(); if (roleName != null) { if (logger.isDebugEnabled()) logger.debug("Saving role '" + roleName + "' for user '" + username + "'"); userRoles.add(roleName); } } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate roles", e); } } // Close the context to release the connection ctx.close(); return (String[]) userRoles.toArray(new String[userRoles.size()]); }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetches the supplied user DN.// w w w. j a v a 2s .com * * @param uid the user id * @return the user DN for the supplied uid * @throws NamingException LDAP error obtaining user information. */ protected String selectUserDN(InitialLdapContext ctx, String uid) throws NamingException { String dn = null; String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(principalUidAttrName); if (uidAttr == null) { logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'"); continue; } String uidValue = uidAttr.get().toString(); if (uidValue != null) { dn = sr.getName() + "," + usersCtxDN; if (logger.isDebugEnabled()) logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid + "' DN=" + dn); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + uid + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } return dn; }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetches the supplied user./*from w w w. j a v a2 s. co m*/ * * @param attrValue the user id * @return the user id for the supplied uid * @throws NamingException LDAP error obtaining user information. */ protected String selectUser(String attrId, String attrValue) throws NamingException { String uidValue = null; InitialLdapContext ctx = createLdapInitialContext(); String uidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(uidAttrName); if (uidAttr == null) { logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'"); continue; } uidValue = uidAttr.get().toString(); if (uidValue != null) { if (logger.isDebugEnabled()) logger.debug( "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'"); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + attrValue + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } finally { // Close the context to release the connection ctx.close(); } return uidValue; }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetch the Ldap user attributes to be used as credentials. * * @param uid the user id for whom credentials are required * @return the hash map containing user credentials as name/value pairs * @throws NamingException LDAP error obtaining user credentials. *//*from w w w . j ava 2s. c o m*/ protected HashMap selectCredentials(String uid) throws NamingException { HashMap credentialResultSet = new HashMap(); InitialLdapContext ctx = createLdapInitialContext(); String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); // BasicAttributes matchAttrs = new BasicAttributes(true); // matchAttrs.put(principalUidAttrName, uid); String credentialQueryString = getCredentialQueryString(); HashMap credentialQueryMap = parseQueryString(credentialQueryString); Iterator i = credentialQueryMap.keySet().iterator(); List credentialAttrList = new ArrayList(); while (i.hasNext()) { String o = (String) i.next(); credentialAttrList.add(o); } String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); for (int j = 0; j < credentialAttr.length; j++) { Object credentialObject = attrs.get(credentialAttr[j]).get(); String credentialName = (String) credentialQueryMap.get(credentialAttr[j]); String credentialValue = null; if (logger.isDebugEnabled()) logger.debug("Found user credential '" + credentialName + "' of type '" + credentialObject.getClass().getName() + "" + (credentialObject.getClass().isArray() ? "[" + Array.getLength(credentialObject) + "]" : "") + "'"); // if the attribute value is an array, cast it to byte[] and then convert to // String using proper encoding if (credentialObject.getClass().isArray()) { try { // Try to create a UTF-8 String, we use java.nio to handle errors in a better way. // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is. byte[] credentialData = (byte[]) credentialObject; ByteBuffer in = ByteBuffer.allocate(credentialData.length); in.put(credentialData); in.flip(); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(in); credentialValue = charBuffer.toString(); } catch (CharacterCodingException e) { if (logger.isDebugEnabled()) logger.debug("Can't convert credential value to String using UTF-8"); } } else if (credentialObject instanceof String) { // The credential value must be a String ... credentialValue = (String) credentialObject; } // Check what do we have ... if (credentialValue != null) { // Remove any schema information from the credential value, like the {md5} prefix for passwords. credentialValue = getSchemeFreeValue(credentialValue); credentialResultSet.put(credentialName, credentialValue); } else { // We have a binary credential, leave it as it is ... probably binary value. credentialResultSet.put(credentialName, credentialObject); } if (logger.isDebugEnabled()) logger.debug("Found user credential '" + credentialName + "' with value '" + (credentialValue != null ? credentialValue : credentialObject) + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } finally { // Close the context to release the connection ctx.close(); } return credentialResultSet; }