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:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind) throws AuthenticationException, NamingException { env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal); env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials); DirContext ctx = null; try {// w w w. j a v a2 s .com ctx = new InitialDirContext(env); } catch (NamingException ne) { log.error("Failed to bind as: {}", ldapSecurityPrincipal); } // ensure we have the userPassword attribute at a minimum String[] attributeList = new String[] { "userPassword" }; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(attributeList); sc.setDerefLinkFlag(true); sc.setReturningObjFlag(false); sc.setTimeLimit(5000); String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")"; // Do the search NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc); if (!results.hasMore()) { log.warn("no valid user found."); return false; } SearchResult result = results.next(); log.debug("authenticating user: {}", result.getNameInNamespace()); if (bind) { // setup user context for binding Hashtable<String, String> userEnv = new Hashtable<String, String>(); userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); userEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); userEnv.put(Context.PROVIDER_URL, baseUrl); userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace()); userEnv.put(Context.SECURITY_CREDENTIALS, password); try { new InitialDirContext(userEnv); } catch (NamingException ne) { log.error("failed to authenticate user: " + result.getNameInNamespace()); throw ne; } } else { // get userPassword attribute Attribute up = result.getAttributes().get("userPassword"); if (up == null) { log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace()); return false; } byte[] userPasswordBytes = (byte[]) up.get(); String userPassword = new String(userPasswordBytes); // compare passwords - also handles encodings if (!passwordsMatch(password, userPassword)) { return false; } } return true; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean hasRole(DirContext context, String roleName) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { if (this.useDefaultRoleName) { groupName = roleName;//w ww.j a v a 2s .c o m } else { log.warn("skip group creation as no mapping for roleName:'{}'", roleName); return false; } } NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); return namingEnumeration.hasMore(); } catch (NameNotFoundException e) { log.debug("group {} for role {} not found", groupName, roleName); return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { close(namingEnumeration); } }
From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java
private String searchAttributes(DirContext oDirContext, String sIDAttribute, String sMapperAttribute, String id) throws OAException { String sReturn = null;/* ww w . j av a 2 s.c o m*/ NamingEnumeration oNamingEnumeration = null; try { if (sIDAttribute == null) { _logger.error("No attribute name to map from supplied"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbQuery = new StringBuffer("("); sbQuery.append(sIDAttribute); sbQuery.append("="); sbQuery.append(JNDIUtil.escapeLDAPSearchFilter(id)); sbQuery.append(")"); String sSearchQuery = sbQuery.toString(); String sSearchFor = sMapperAttribute; if (sSearchFor == null) sSearchFor = "*"; SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); oScope.setReturningAttributes(new String[] { sSearchFor }); try { oNamingEnumeration = oDirContext.search(_sDNBase, sSearchQuery, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(sSearchQuery); sbFailed.append(" while searching for attributes for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } if (!oNamingEnumeration.hasMore()) { _logger.debug("No result when searching for: " + sSearchQuery); } else { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); if (sMapperAttribute == null) { sReturn = oSearchResult.getName(); sReturn += "," + _sDNBase; } else { Attributes oSearchedAttributes = oSearchResult.getAttributes(); Attribute attrMapping = oSearchedAttributes.get(sMapperAttribute); if (attrMapping == null) { _logger.debug("Mapping attribute not found: " + sMapperAttribute); } else { Object oValue = attrMapping.get(); if (!(oValue instanceof String)) { StringBuffer sbError = new StringBuffer("Returned value for mapping attribute '"); sbError.append(_sMapperAttribute); sbError.append("' has a value which is not of type 'String'"); _logger.error(sbError.toString()); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } sReturn = (String) oValue; } } } } catch (OAException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch mapping attribute for id: " + id, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for id: " + id, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for id: " + id, e); } } } return sReturn; }
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 w w . ja va2 s .com*/ 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:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) { Object[] filterArguments = { _roleObjectClass }; SearchControls ctls = new SearchControls(); ctls.setDerefLinkFlag(true);/*from w w w .j a v a 2 s . c om*/ ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>(); try { NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls); while (results.hasMoreElements()) { SearchResult result = results.nextElement(); Attributes attributes = result.getAttributes(); if (attributes == null) { continue; } Attribute roleAttribute = attributes.get(_roleNameAttribute); Attribute memberAttribute = attributes.get(_roleMemberAttribute); if (roleAttribute == null || memberAttribute == null) { continue; } NamingEnumeration role = roleAttribute.getAll(); NamingEnumeration members = memberAttribute.getAll(); if (!role.hasMore() || !members.hasMore()) { continue; } String roleName = (String) role.next(); if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) { roleName = roleName.replace(_rolePrefix, ""); } while (members.hasMore()) { String member = (String) members.next(); Matcher roleMatcher = rolePattern.matcher(member); if (!roleMatcher.find()) { continue; } String roleMember = roleMatcher.group(1); List<String> memberOf; if (roleMemberOfMap.containsKey(roleMember)) { memberOf = roleMemberOfMap.get(roleMember); } else { memberOf = new ArrayList<String>(); } memberOf.add(roleName); roleMemberOfMap.put(roleMember, memberOf); } } } catch (NamingException e) { e.printStackTrace(); } return roleMemberOfMap; }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return the user dn of an ldap entry/*from w w w . jav a 2 s .c o m*/ * * search: base, filter, attrs, user, pass * @return */ protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter, String[] attributes) { SearchResult ret = null; Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11); bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); bindEnv.put(Context.PROVIDER_URL, getLdapUrl()); // remove null attributes List<String> goodAttributes = new ArrayList<String>(); for (String s : attributes) { if (s != null) { goodAttributes.add(s); } } // get the DN DirContext authenticationContext; try { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setReturningObjFlag(true); ctls.setReturningAttributes(goodAttributes.toArray(new String[0])); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Authenticate as User and password if (bindUser != null && bindPass != null) { log.debug("NBinding with credential as user: " + bindUser); bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser); bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass); } authenticationContext = new InitialDirContext(bindEnv); // %u, %d in baseDN are still expanded NamingEnumeration<SearchResult> answer; try { answer = authenticationContext.search(base, filter, ctls); if (answer.hasMore()) { ret = (SearchResult) answer.next(); } } catch (NamingException e) { log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage()); } authenticationContext.close(); return ret; } catch (NamingException e) { log.error("Error while creating context: " + e.getMessage()); if (e.getCause() != null) { log.error("Error is: " + e.getCause().getMessage()); } return null; } }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * /* w w w. java2s. c om*/ * @param search * @param searchValue * @param attributeNames * @return naming enumeration */ protected NamingEnumeration getLdapResults(Search search, String searchValue, String[] attributeNames) { DirContext context = null; NamingEnumeration results = null; String filter = search.getParam("filter"); if (filter == null) { log.error("Search filter not found for search type: " + search.getSearchType()); return results; } filter = filter.replaceAll("%TERM%", escapeSearchFilter(searchValue)); String base = search.getParam("base"); if (base == null) { base = ""; log.error("Search base not found for: " + search.getSearchType() + ". Using base \"\" "); } int scopeNum = -1; String scope = search.getParam("scope"); if (scope != null) { scopeNum = getScope(scope); } if (scopeNum == -1) { scopeNum = SearchControls.SUBTREE_SCOPE; log.error("Search scope not found for: " + search.getSearchType() + ". Using scope SUBTREE_SCOPE."); } log.debug("searchType: " + search.getSearchType() + " filter: " + filter + " base: " + base + " scope: " + scope); try { context = new InitialDirContext(this.environment); SearchControls constraints = new SearchControls(); constraints.setSearchScope(scopeNum); constraints.setReturningAttributes(attributeNames); results = context.search(base, filter, constraints); } catch (AuthenticationException ex) { log.error("Ldap Authentication Exception: " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("Ldap NamingException: " + ex.getMessage(), ex); } finally { if (context != null) { try { context.close(); } catch (NamingException ne) { // squelch, since it is already closed } } } return results; }
From source file:ldap.ActiveLoginImpl.java
/** * Returns whether this user is listed in the admin users role * * @param login// w w w . ja v a 2s . com * @return * @throws Exception */ public boolean isAdmin(String login, DirContext context, String DN) throws Exception { NamingEnumeration result = null; String[] returnAttributes = new String[] { "uniqueMember" }; /* specify search constraints to search subtree */ SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.OBJECT_SCOPE); constraints.setCountLimit(0); constraints.setTimeLimit(0); constraints.setReturningAttributes(returnAttributes); /* Entry user = null; try { user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context); } catch (NamingException e) { throw new LdapException("getUser NamingException" + e.getMessage(), e); } String DN = null; if (user == null) { logger.info("USER DOES NOT EXIST"); return false; } else { DN = user.getName().toString(); if (DN != null) { logger.info("DN = " + DN); } } */ //result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember="+getUserDN(login)+")", constraints); result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember=" + DN + ")", constraints); if (result.hasMore()) { if (debug) { SearchResult sResult = (SearchResult) result.next(); logger.info("Read Admin Roles Object with members: " + sResult.getAttributes().toString()); } return true; } else if (debug) logger.info("Failed to find admin object with member " + DN); return false; }
From source file:it.webappcommon.lib.LDAPHelper.java
/** * @param args//from w w w .j a v a 2 s . c om * the command line arguments */ // public static void main(String[] args) { private List<UserInfo> search(String filter) throws NamingException { DirContext ctx = null; SearchControls ctls = null; Properties env = new Properties(); List<UserInfo> res = new ArrayList<UserInfo>(); boolean trovatiRisultati = false; env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port); env.put(Context.SECURITY_AUTHENTICATION, "simple"); if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) { env.put(Context.SECURITY_PRINCIPAL, loginUserName); } else { env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName); } env.put(Context.SECURITY_CREDENTIALS, loginPassword); try { ctx = new InitialDirContext(env); ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // String filter = ""; // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))"; // filter = FILTER_USERS_ACTIVE; // Tutti i membri di un gruppo // (objectCategory=user)(memberOf=CN=QA Users,OU=Help // Desk,DC=dpetri,DC=net) // ESEMPI // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm // Account disabled // (UserAccountControl:1.2.840.113556.1.4.803:=2) NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls); UserInfo userInfo = null; while (answer.hasMoreElements()) { trovatiRisultati = true; SearchResult a = answer.nextElement(); // logger.debug(a.getNameInNamespace()); Attributes result = a.getAttributes(); if (result == null) { // System.out.print("Attributi non presenti"); } else { NamingEnumeration<? extends Attribute> attributi = result.getAll(); userInfo = new UserInfo(); while (attributi.hasMoreElements()) { Attribute att = attributi.nextElement(); // logger.debug(att.getID()); String value = ""; // for (NamingEnumeration vals = att.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())) // ; NamingEnumeration<?> vals = att.getAll(); while (vals.hasMoreElements()) { Object val = vals.nextElement(); // logger.debug("\t" + val); value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString(); } if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) { // userInfo.setFIELD_ACCOUNT_NAME(value); userInfo.setAccount(value); } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) { // userInfo.setFIELD_COGNOME(value); userInfo.setCognome(value); } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) { // userInfo.setFIELD_EMAIL(value); userInfo.setEmail(value); } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) { // userInfo.setFIELD_GROUPS(value); userInfo.setGruppi(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) { // userInfo.setFIELD_NOME(value); userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) { // userInfo.setFIELD_NOME_COMPLETO(value); userInfo.setNomeCompleto(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) { // userInfo.setFIELD_NOME_VISUALIZZATO(value); // userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) { // userInfo.setFIELD_TEL(value); userInfo.setTel(value); } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) { // userInfo.setFIELD_UFFICIO(value); userInfo.setUfficio(value); } // res.put(att.getID(), value); } // Attribute attr = result.get("cn"); // if (attr != null) { // logger.debug("cn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("sn"); // if (attr != null) { // logger.debug("sn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("mail"); // if (attr != null) { // logger.debug("mail:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // // attr = result.get("uid"); // // if (attr != null) { // // logger.debug("uid:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } // // // // attr = result.get("userPassword"); // // if (attr != null) { // // logger.debug("userPassword:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } if (userInfo != null) { res.add(userInfo); } } } } catch (NamingException ne) { // ne.printStackTrace(); logger.error(ne); throw ne; } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception e) { } } // Azzero l'hash map if (!trovatiRisultati) { res = null; } return res; }
From source file:ldap.SearchUtility.java
/** * * @param searchBase/*from www. ja v a 2 s .c om*/ * @param regexp * @param pageSize * @param pageNumber * @return a list of matching users. * @throws NamingException */ public List<Entry> getUsers(LdapName searchBase, String regexp, int pageSize, int pageNumber, ArrayList<String> attributes, DirContext context) throws NamingException { Pattern pattern = null; if (regexp != null) pattern = Pattern.compile(regexp); /* * Figure out an ldap search filter. Note that unless an ORDERING matching rule is defined on the server * for the attribute we are searching (and they usually aren't, since it requires extra indexing on the * server), we cannot use ldap greater than / less than search filters to find * a range of users, and have to do this search in code using a regular expression. */ //String filter = "(objectClass=" + Config.USER_OBJECTCLASS + ")"; String filter = ""; if (LdapConstants.ldapObjectClassEmployeeEnable) { filter = "(objectClass=" + LdapConstants.ldapObjectClassEmployee + ")"; } SearchControls controls = getSearchControls(); String[] attributesToReturn; if (attributes == null) { attributesToReturn = null; // a JNDI special value that means 'return everything' } else { //attributes.add(Config.USER_NAMING_ATT); attributes.add(LdapConstants.ldapAttrUid); attributesToReturn = attributes.toArray(new String[] {}); } if (controls != null) { controls.setReturningAttributes(attributesToReturn); } else { logger.info("controls is null"); } // do the directory search NamingEnumeration<SearchResult> userResults = context.search(searchBase, filter, controls); if (userResults == null) { logger.info("userResults is Null in getUsers()"); return null; } else { // parse the results, looking for entries that match our regexp ArrayList<Entry> users = new ArrayList<Entry>(); while (userResults.hasMore()) { SearchResult userResult = userResults.next(); Entry userEntry = new Entry(userResult); //String text = userEntry.getValue(Config.USER_NAMING_ATT).toUpperCase(); String text = userEntry.getValue(LdapConstants.ldapAttrUid).toUpperCase(); if (pattern == null) { users.add(userEntry); } else { Matcher matcher = pattern.matcher(text); if (matcher.find()) { users.add(userEntry); } } } // sort them alphabeticaly by user naming attribute Collections.sort(users); // trim the results to the page requested (if any) if (pageSize > 0) { ArrayList<Entry> userPage = new ArrayList<Entry>(pageSize); int startPos = pageSize * pageNumber; int size = users.size(); for (int i = startPos; i < (startPos + pageSize); i++) { if (i < size) { userPage.add(users.get(i)); } } users = userPage; } // add 'synthetic' attributes for for (Entry user : users) { fillInSyntheticAttributes(user); } // return the final user list return users; } // else }