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:org.infoscoop.account.ldap.LDAPAccountManager.java
private List searchGroupMember(DirContext context, Map filters) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); Set userList = new HashSet(); String filter = buildFilter(filters); if (log.isInfoEnabled()) log.info("Search User from " + userBase + " by " + filter); NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls); while (searchResultEnum.hasMore()) { SearchResult searchResult = (SearchResult) searchResultEnum.next(); Attributes attrs = searchResult.getAttributes(); String dn = searchResult.getName() + "," + groupBase; String uniquememberAttrName = "uniqueMember"; if (this.propAttrMap.containsKey("org_member")) { try { uniquememberAttrName = (String) this.propAttrMap.get("org_member"); } catch (Exception ex) { //ignore }//from w w w . java 2 s . c o m } Attribute uniquememberAttr = attrs.get(uniquememberAttrName); if (uniquememberAttr == null) continue; NamingEnumeration memberDNs = uniquememberAttr.getAll(); while (memberDNs.hasMoreElements()) { //System.out.println(memberDNs[j]); userList.add(memberDNs.next());//DN of user } } List members = new ArrayList(); for (Iterator userDns = userList.iterator(); userDns.hasNext();) { /* Next directory entry */ String userDn = (String) userDns.next(); Attributes userEntry = null; try { userEntry = context.getAttributes(userDn);//DN of user } catch (Exception e) { log.error(userDn + ": " + e.getMessage()); } if (userEntry == null) continue; LDAPAccount user = createLDAPUser(userDn, userEntry); if (user.getUid() == null) continue; members.add(user); } return members; }
From source file:org.jasig.portal.groups.ldap.LDAPGroupStore.java
public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException { if (type != group && type != iperson) return new EntityIdentifier[0]; ArrayList ids = new ArrayList(); switch (method) { case STARTS_WITH: query = query + "*"; break;/*from w w w . j ava2 s . c o m*/ case ENDS_WITH: query = "*" + query; break; case CONTAINS: query = "*" + query + "*"; break; } query = namefield + "=" + query; DirContext context = getConnection(); NamingEnumeration userlist = null; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { keyfield }); try { userlist = context.search(usercontext, query, sc); } catch (NamingException nex) { log.error("LDAPGroupStore: Unable to perform filter " + query, nex); } ArrayList keys = new ArrayList(); processLdapResults(userlist, keys); String[] k = (String[]) keys.toArray(new String[0]); for (int i = 0; i < k.length; i++) { ids.add(new EntityIdentifier(k[i], iperson)); } return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]); }
From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java
/** * Authenticates the user./* ww w .j a v a 2 s. c o m*/ */ public synchronized void authenticate() throws PortalSecurityException { this.isauth = false; ILdapServer ldapConn; String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME); if (propFile != null && propFile.length() > 0) ldapConn = LdapServices.getLdapServer(propFile); else ldapConn = LdapServices.getDefaultLdapServer(); String creds = new String(this.myOpaqueCredentials.credentialstring); if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("") && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) { DirContext conn = null; NamingEnumeration results = null; StringBuffer user = new StringBuffer("("); String first_name = null; String last_name = null; user.append(ldapConn.getUidAttribute()).append("="); user.append(this.myPrincipal.UID).append(")"); if (log.isDebugEnabled()) log.debug("SimpleLdapSecurityContext: Looking for " + user.toString()); try { conn = ldapConn.getConnection(); // set up search controls SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(attributes); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // do lookup if (conn != null) { try { results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls); if (results != null) { if (!results.hasMore()) log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID); while (results != null && results.hasMore()) { SearchResult entry = (SearchResult) results.next(); StringBuffer dnBuffer = new StringBuffer(); dnBuffer.append(entry.getName()).append(", "); dnBuffer.append(ldapConn.getBaseDN()); Attributes attrs = entry.getAttributes(); first_name = getAttributeValue(attrs, ATTR_FIRSTNAME); last_name = getAttributeValue(attrs, ATTR_LASTNAME); // re-bind as user conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL); conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS); conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString()); conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, this.myOpaqueCredentials.credentialstring); searchCtls = new SearchControls(); searchCtls.setReturningAttributes(new String[0]); searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE); String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)"; log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for " + attrSearch); conn.search(dnBuffer.toString(), attrSearch, searchCtls); this.isauth = true; this.myPrincipal.FullName = first_name + " " + last_name; log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " (" + this.myPrincipal.FullName + ") is authenticated"); // Since LDAP is case-insensitive with respect to uid, force // user name to lower case for use by the portal this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase(); } // while (results != null && results.hasMore()) } else { log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID); } } catch (AuthenticationException ae) { log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID); } catch (Exception e) { log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ", e); throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e + " with user: " + this.myPrincipal.UID); } finally { ldapConn.releaseConnection(conn); } } else { log.error("LDAP Server Connection unavalable"); } } catch (final NamingException ne) { log.error("Error geting connection to LDAP server.", ne); } } else { log.error("Principal or OpaqueCredentials not initialized prior to authenticate"); } // Ok...we are now ready to authenticate all of our subcontexts. super.authenticate(); return; }
From source file:org.jkcsoft.java.util.JndiHelper.java
public static Map getUserInfo(BehavioralContext ctx, String userName) throws NamingException { Map infoMap = null;//w ww .j ava2s . c o m Configuration cfg = ctx.getConfig(); // String searchRelativeDc = cfg.getString(Constants.KEY_AD_USER_NODE_DN); String theFilter = LDAP_USER_SAMACCOUNTNAME + "=" + userName; List theAttrsList = new Vector(Arrays.asList(ldapUserAttrs)); theAttrsList.addAll(Arrays.asList(ldapTopAttrs)); int countLimit = 1000; int timeLimitMillis = 30000; boolean returnObject = false; boolean derefObj = true; SearchControls scs = new SearchControls(SearchControls.SUBTREE_SCOPE, countLimit, timeLimitMillis, (String[]) theAttrsList.toArray(new String[0]), returnObject, derefObj); DirContext rootCtx = getTsessAccountContext(ctx); try { log.debug("Search params name[" + searchRelativeDc + "] " + "filter[" + theFilter + "] controls[" + scs + "]"); NamingEnumeration results = rootCtx.search(searchRelativeDc, theFilter, scs); if (results == null || !results.hasMore()) throw new NamingException("User LDAP entry not found"); SearchResult searchResult = ((SearchResult) results.next()); if (searchResult == null) throw new NamingException("User LDAP entry not found"); if (log.isTraceEnabled()) { logLdap(log, 0, 0, searchResult); } Attributes userLdapAttrs = searchResult.getAttributes(); infoMap = new HashMap(); for (Iterator attrIter = theAttrsList.iterator(); attrIter.hasNext();) { loadMap(infoMap, userLdapAttrs, (String) attrIter.next()); } } finally { safeClose(rootCtx); } return infoMap; }
From source file:org.lsc.jndi.JndiServices.java
/** * Return the LDAP schema.//from w ww. ja va 2 s .c om * * @param attrsToReturn * list of attribute names to return (or null for all * 'standard' attributes) * @return the map of name => attribute * @throws NamingException * thrown if something goes wrong (bad */ @SuppressWarnings("unchecked") public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException { Map<String, List<String>> attrsResult = new HashMap<String, List<String>>(); // connect to directory Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment(); String baseUrl = (String) props.get(Context.PROVIDER_URL); baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/')); props.put(Context.PROVIDER_URL, baseUrl); DirContext schemaCtx = new InitialLdapContext(props, null); // find schema entry SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningAttributes(new String[] { "subschemaSubentry" }); NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc); SearchResult sr = null; Attribute subschemaSubentry = null; String subschemaSubentryDN = null; if (schemaDnSR.hasMore()) { sr = schemaDnSR.next(); } if (sr != null) { subschemaSubentry = sr.getAttributes().get("subschemaSubentry"); } if (subschemaSubentry != null && subschemaSubentry.size() > 0) { subschemaSubentryDN = (String) subschemaSubentry.get(); } if (subschemaSubentryDN != null) { // get schema attributes from subschemaSubentryDN Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN, attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" }); if (schemaAttrs != null) { for (String attr : attrsToReturn) { Attribute schemaAttr = schemaAttrs.get(attr); if (schemaAttr != null) { attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll())); } } } } return attrsResult; }
From source file:org.nuxeo.ecm.directory.ldap.ExternalLDAPDirectoryFeature.java
protected void destroyRecursively(String dn, DirContext ctx, int limit) throws NamingException { if (limit == 0) { log.warn("Reach recursion limit, stopping deletion at" + dn); return;//from w w w . j a v a 2 s . c om } SearchControls scts = new SearchControls(); scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> children = ctx.search(dn, "(objectClass=*)", scts); try { while (children.hasMore()) { SearchResult child = children.next(); String subDn = child.getName(); subDn = subDn + ',' + dn; destroyRecursively(subDn, ctx, limit); } } catch (SizeLimitExceededException e) { log.warn("SizeLimitExceededException: trying again on partial results " + dn); if (limit == -1) { limit = 100; } destroyRecursively(dn, ctx, limit - 1); } ctx.destroySubcontext(dn); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectoryTestCase.java
protected void destroyRecursively(String dn, DirContext ctx, int limit) throws NamingException { if (limit == 0) { log.warn("Reach recursion limit, stopping deletion at" + dn); return;//from w ww. j a v a 2 s.c o m } SearchControls scts = new SearchControls(); scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); String providerUrl = (String) ctx.getEnvironment().get(Context.PROVIDER_URL); NamingEnumeration<SearchResult> children = ctx.search(dn, "(objectClass=*)", scts); try { while (children.hasMore()) { SearchResult child = children.next(); String subDn = child.getName(); if (!USE_EXTERNAL_TEST_LDAP_SERVER && subDn.endsWith(providerUrl)) { subDn = subDn.substring(0, subDn.length() - providerUrl.length() - 1); } else { subDn = subDn + ',' + dn; } destroyRecursively(subDn, ctx, limit); } } catch (SizeLimitExceededException e) { log.warn("SizeLimitExceededException: trying again on partial results " + dn); if (limit == -1) { limit = 100; } destroyRecursively(dn, ctx, limit - 1); } ctx.destroySubcontext(dn); }
From source file:org.nuxeo.wizard.RouterServlet.java
public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context ctx = Context.instance(req); ParamCollector collector = ctx.getCollector(); String refreshParam = req.getParameter("refresh"); String directoryType = collector.getConfigurationParam("nuxeo.directory.type"); if ("true".equals(refreshParam)) { currentPage.dispatchToJSP(req, resp); return;/*from w w w . ja va2 s . com*/ } if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam) || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) { try { if ("checkNetwork".equals(refreshParam)) { bindLdapConnection(collector, false); ctx.trackInfo("nuxeo.ldap.url", "info.host.found"); } else if ("checkAuth".equals(refreshParam)) { bindLdapConnection(collector, true); ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success"); } else { DirContext dirContext = new InitialDirContext(getContextEnv(collector, true)); String searchScope; String searchBaseDn; String searchClass; String searchFilter; if ("checkUserLdapParam".equals(refreshParam)) { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope"); searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter"); } else { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter"); searchClass = ""; } SearchControls scts = new SearchControls(); if ("onelevel".equals(searchScope)) { scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); } else { scts.setSearchScope(SearchControls.SUBTREE_SCOPE); } String filter = String.format("(&(%s)(objectClass=%s))", searchFilter.isEmpty() ? "objectClass=*" : searchFilter, searchClass.isEmpty() ? "*" : searchClass); NamingEnumeration<SearchResult> results; try { results = dirContext.search(searchBaseDn, filter, scts); if (!results.hasMore()) { ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult"); } else { SearchResult result = results.next(); if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) { // try not to display the root of the search // base DN result = results.next(); } ctx.trackInfo("dn", result.getNameInNamespace()); Attributes attributes = result.getAttributes(); NamingEnumeration<String> ids = attributes.getIDs(); String id; StringBuilder sb; while (ids.hasMore()) { id = ids.next(); NamingEnumeration<?> values = attributes.get(id).getAll(); sb = new StringBuilder(); while (values.hasMore()) { sb.append(values.next()).append(" , "); } ctx.trackInfo(id, sb.substring(0, sb.length() - 3)); } } } catch (NameNotFoundException e) { ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn"); log.warn(e); } dirContext.close(); } } catch (AuthenticationException e) { ctx.trackError("nuxeo.ldap.auth", "error.auth.failed"); log.warn(e); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.url", "error.host.not.found"); log.warn(e); } } // Form submit if (!"default".equals(directoryType) && refreshParam.isEmpty()) { // first check bind to LDAP server try { bindLdapConnection(collector, true); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed"); log.warn(e); } // then check mandatory fields if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required"); } String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage"); if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) { if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required"); } } if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) { if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) { ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required"); } if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) { ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required"); } } } if (ctx.hasErrors() || ctx.hasInfos()) { currentPage.dispatchToJSP(req, resp); } else { currentPage.next().dispatchToJSP(req, resp, true); } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Find the user dn with its uid/*from w w w. jav a2 s .c o m*/ * * @param uid * @param ctx * @return user's dn */ private String searchUserDN(final String uid, final DirContext ctx) { if (ctx == null) { return null; } final List<String> ldapBases = LDAPLoginModule.getLdapBases(); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final String[] serachAttr = { "dn" }; final String ldapUserIDAttribute = LDAPLoginModule .mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))"; final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(serachAttr); String userDN = null; for (final String ldapBase : ldapBases) { try { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { final SearchResult result = enm.next(); userDN = result.getNameInNamespace(); } if (userDN != null) { break; } } catch (final NamingException e) { logError("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e); } } return userDN; }
From source file:org.openadaptor.auxil.connector.jndi.JNDISearch.java
/** * Execute this search against a DirContext. * <p>//from ww w . j ava2 s .c om * The search will be run against each configured searchBase in turn, returning a NamingEnumeration will all of the * matching entries the search yields. * * @param context * a DirContext against which the search is to be executed. * @return NamingEnumeration This will contain all matching entries found. * @throws NamingException * If searchBases does not contain at least one search base, or if the search fails for any reason. */ public NamingEnumeration execute(DirContext context) throws NamingException { if (_searchBases == null || _searchBases.length <= 0) { String error = "Property searchBases may not be <null> and must have at least one value"; log.error(error); throw new NamingException(error); } int searchCount = _searchBases.length; // One search for each searchBase NamingEnumeration[] results = new NamingEnumeration[searchCount]; boolean useAttributes = _attributes != null; String[] origAttributes = searchControls.getReturningAttributes(); if (useAttributes) { searchControls.setReturningAttributes(_attributes); } for (int i = 0; i < searchCount; i++) { String base = _searchBases[i]; log.debug("Executing search against base: " + base + " using filter: " + _filter + " and constraints: " + searchControls + ""); try { results[i] = context.search(base, _filter, searchControls); } catch (NameNotFoundException e) { if (ignoreFailedLookup) { results = new NamingEnumeration[0]; // e.g. we do not care if enrichment lookup failed log.error("Ignoring NameNotFoundException from JNDI lookup", e); break; } else { throw e; } } } if (useAttributes) { // Put the old ones back. searchControls.setReturningAttributes(origAttributes); } return new MultiBaseJNDISearchResults(this, results); }