List of usage examples for javax.naming.directory SearchResult getNameInNamespace
public String getNameInNamespace()
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches single parent, cutting the dn and trying to get the given entry. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) *//*from w ww . j a v a2 s . c om*/ @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { Set<String> sourceIds = new TreeSet<>(); String targetDn = null; // step #1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId, true); if (targetLdapEntry == null) { // no parent accessible => return empty list return EMPTY_STRING_LIST; } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + targetId, e); } // step #2: search for entries that reference parent dn in the // source directory and collect its id LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String parentDn = getParentDn(targetDn); String filterExpr = String.format("(&%s)", ldapSourceDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapSourceDirectory.getSearchControls(true); sctls.setSearchScope(SearchControls.OBJECT_SCOPE); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", targetId, parentDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(parentDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(sourceSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { sourceIds.add(value.toString()); // only supposed to get one result anyway break; } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetDn, e); } return new ArrayList<>(sourceIds); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches children, onelevel or subtree given the reference configuration. * <p>//from w ww. j a v a 2s.co m * Removes entries with same id than parent to only get real children. * * @see org.nuxeo.ecm.directory.Reference#getTargetIdsForSource(String) */ // TODO: optimize reusing the same ldap session (see LdapReference optim // method) @Override public List<String> getTargetIdsForSource(String sourceId) throws DirectoryException { Set<String> targetIds = new TreeSet<>(); String sourceDn = null; // step #1: fetch the dn of the sourceId entry in the source // directory by the static dn valued strategy LDAPDirectory sourceDir = getSourceLDAPDirectory(); try (LDAPSession sourceSession = (LDAPSession) sourceDir.getSession()) { SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId, true); if (sourceLdapEntry == null) { throw new DirectoryException(sourceId + " does not exist in " + sourceDirectoryName); } sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + sourceId, e); } // step #2: search for entries with sourceDn as base dn and collect // their ids LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory(); String filterExpr = String.format("(&%s)", ldapTargetDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapTargetDirectory.getSearchControls(true); sctls.setSearchScope(getScope()); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getTargetIdsForSource(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", sourceId, sourceDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = targetSession.dirContext.search(sourceDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(targetSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { // always remove self as child String targetId = value.toString(); if (!sourceId.equals(targetId)) { targetIds.add(targetId); } } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + sourceDn, e); } return new ArrayList<>(targetIds); }
From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java
public Map<String, String> findLdapUserDetails(String userName) { Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord()); HashMap<String, String> userDetails = new HashMap<String, String>(); // Load our LDAP specific properties Properties env = getProperties(systemConfig); // Load the BaseDN String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN); // Load the LoginProperty String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty); if (loginProperty == null) { // Use the default loginProperty = "cn"; }//w ww . jav a 2s . c o m // Load any information we may need to bind String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN); String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW); // Load any search filter String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); // Add the search filter if specified. This only allows for a single search filter.. i.e. foo=bar. String filter; if ((searchFilter != null) && (searchFilter.length() != 0)) { filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))"; } else { filter = "(" + loginProperty + "=" + userName + ")"; } log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName); // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls); if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]); // Nothing found for this DN, move to the next one if we have one. continue; } // We use the first match SearchResult si = answer.next(); //generate the DN String userDN = null; try { userDN = si.getNameInNamespace(); } catch (UnsupportedOperationException use) { userDN = si.getName(); if (userDN.startsWith("\"")) { userDN = userDN.substring(1, userDN.length()); } if (userDN.endsWith("\"")) { userDN = userDN.substring(0, userDN.length() - 1); } userDN = userDN + "," + baseDNs[x]; } userDetails.put("dn", userDN); // Construct the UserDN NamingEnumeration<String> keys = si.getAttributes().getIDs(); while (keys.hasMore()) { String key = keys.next(); Attribute value = si.getAttributes().get(key); if ((value != null) && (value.get() != null)) { userDetails.put(key, value.get().toString()); } } return userDetails; } return userDetails; } catch (NamingException e) { throw new RuntimeException(e); } }
From source file:org.sonar.plugins.ldap.LdapAuthenticator.java
/** * Authenticate the user against LDAP servers until first success. * @param login The login to use./*ww w. j a va2s . c o m*/ * @param password The password to use. * @return false if specified user cannot be authenticated with specified password on any LDAP server */ public boolean authenticate(String login, String password) { for (String ldapKey : userMappings.keySet()) { final String principal; if (contextFactories.get(ldapKey).isSasl()) { principal = login; } else { final SearchResult result; try { result = userMappings.get(ldapKey).createSearch(contextFactories.get(ldapKey), login) .findUnique(); } catch (NamingException e) { LOG.debug("User {} not found in server {}: {}", login, ldapKey, e.getMessage()); continue; } if (result == null) { LOG.debug("User {} not found in {}", login, ldapKey); continue; } principal = result.getNameInNamespace(); } boolean passwordValid; if (contextFactories.get(ldapKey).isGssapi()) { passwordValid = checkPasswordUsingGssapi(principal, password, ldapKey); } else { passwordValid = checkPasswordUsingBind(principal, password, ldapKey); } if (passwordValid) { return true; } } LOG.debug("User {} not found", login); return false; }
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "group.list", required = { "domain" }) @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> listGroups(OperationContext opContext) throws NamingException { String domain = (String) opContext.getParams().get("domain"); DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal(); DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> searchResults = userDirContext.search(nameHelper.getGroupsBaseDn(domainDn), "(cn=*)", controls); List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>(); while (searchResults.hasMore()) { SearchResult sr = searchResults.next(); if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) { HashMap<String, Object> group = new HashMap<String, Object>(); group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId()); groups.add(group);/*from ww w . j a v a 2 s . c om*/ } } HashMap<String, Object> response = new HashMap<String, Object>(); response.put("groups", groups); return response; }
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "user.membership.get", required = { "userId" }) @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> listMermbershipGroups(OperationContext opContext) throws NamingException { String userId = (String) opContext.getParams().get("userId"); UserDn userDn = nameHelper.newUserDnFromId(userId); DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain()); DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> searchResults = userDirContext.search( nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())), "(uniqueMember=" + userDn.toString() + ")", controls); List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>(); while (searchResults.hasMore()) { SearchResult sr = searchResults.next(); if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) { HashMap<String, Object> group = new HashMap<String, Object>(); group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId()); groups.add(group);/*from w w w . j a v a 2 s .c o m*/ } } HashMap<String, Object> response = new HashMap<String, Object>(); response.put("groups", groups); return response; }
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;// ww w . ja v a2 s . c o m try { 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:ru.runa.wfe.security.logic.LdapLogic.java
private int synchronizeGroups(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName) throws NamingException { int changesCount = 0; List<Group> existingGroupsList = executorDao.getAllGroups(); Map<String, Group> existingGroupsByLdapNameMap = Maps.newHashMap(); for (Group group : existingGroupsList) { if (!Strings.isNullOrEmpty(group.getLdapGroupName())) { existingGroupsByLdapNameMap.put(group.getLdapGroupName(), group); }/*from w ww . j av a 2s . co m*/ } Set<Group> ldapGroupsToDelete = Sets.newHashSet(); if (LdapProperties.isSynchronizationDeleteExecutors()) { Set<Executor> ldapExecutors = executorDao.getGroupChildren(importGroup); for (Executor executor : ldapExecutors) { if (executor instanceof Group) { ldapGroupsToDelete.add((Group) executor); } } } SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); Map<String, SearchResult> groupResultsByDistinguishedName = Maps.newHashMap(); for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) { NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_GROUP_FILTER, controls); while (list.hasMore()) { SearchResult searchResult = list.next(); if (searchResult.getAttributes().get(ATTR_GROUP_MEMBER) == null) { continue; } groupResultsByDistinguishedName.put(searchResult.getNameInNamespace(), searchResult); } } for (SearchResult searchResult : groupResultsByDistinguishedName.values()) { String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME); String description = getStringAttribute(searchResult, LdapProperties.getSynchronizationGroupDescriptionAttribute()); ToStringHelper toStringHelper = MoreObjects.toStringHelper("group info"); toStringHelper.add("name", name).add("description", description).omitNullValues(); log.debug("Read " + toStringHelper.toString()); Group group = existingGroupsByLdapNameMap.get(name); if (group == null) { if (!LdapProperties.isSynchronizationCreateExecutors()) { continue; } group = new Group(name, description); group.setLdapGroupName(name); log.info("Creating " + group); executorDao.create(group); executorDao.addExecutorsToGroup(Lists.newArrayList(group), importGroup); permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), group); changesCount++; } else { ldapGroupsToDelete.remove(group); if (LdapProperties.isSynchronizationUpdateExecutors()) { List<IChange> changes = Lists.newArrayList(); if (isAttributeNeedsChange(description, group.getDescription())) { changes.add(new AttributeChange("description", group.getDescription(), description)); group.setDescription(description); executorDao.update(group); } if (executorDao.removeExecutorFromGroup(group, wasteGroup)) { changes.add(new Change("waste group removal")); } if (executorDao.addExecutorToGroup(group, importGroup)) { changes.add(new Change("import group addition")); } if (!changes.isEmpty()) { log.info("Updating " + group + ": " + changes); changesCount++; } } } Set<Actor> actorsToDelete = Sets.newHashSet(executorDao.getGroupActors(group)); Set<Actor> actorsToAdd = Sets.newHashSet(); Set<Actor> groupTargetActors = Sets.newHashSet(); fillTargetActorsRecursively(dirContext, groupTargetActors, searchResult, groupResultsByDistinguishedName, actorsByDistinguishedName); for (Actor targetActor : groupTargetActors) { if (!actorsToDelete.remove(targetActor)) { actorsToAdd.add(targetActor); } } if (actorsToAdd.size() > 0) { log.info("Adding to " + group + ": " + actorsToAdd); executorDao.addExecutorsToGroup(actorsToAdd, group); changesCount++; } if (actorsToDelete.size() > 0) { executorDao.removeExecutorsFromGroup(Lists.newArrayList(actorsToDelete), group); changesCount++; } } if (LdapProperties.isSynchronizationDeleteExecutors() && ldapGroupsToDelete.size() > 0) { executorDao.removeExecutorsFromGroup(ldapGroupsToDelete, importGroup); executorDao.addExecutorsToGroup(ldapGroupsToDelete, wasteGroup); log.info("Inactivating " + ldapGroupsToDelete); changesCount += ldapGroupsToDelete.size(); } return changesCount; }
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "user.remove", required = { "userId" }) @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> removeUser(OperationContext opContext) throws NamingException { String userId = (String) opContext.getParams().get("userId"); DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal(); UserDn userDn = nameHelper.newUserDnFromId(userId); DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain()); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> searchResults = userDirContext.search( nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())), "(uniqueMember=" + userDn.toString() + ")", controls); while (searchResults.hasMore()) { SearchResult sr = searchResults.next(); DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(sr.getNameInNamespace()); dca.removeAttributeValue("uniqueMember", userDn.toString()); userDirContext.modifyAttributes(sr.getNameInNamespace(), dca.getModificationItems()); }/*w w w. ja va 2 s .com*/ userDirContext.unbind(userDn); HashMap<String, Object> response = new HashMap<String, Object>(); response.put("success", true); return response; }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private void serialize(List results, Config config, ContentHandler ch) { try {//from w w w . j ava 2s . c o m ch.startDocument(); ch.startElement("", "results", "results", SAXUtils.EMPTY_ATTRIBUTES); for (Iterator i = results.iterator(); i.hasNext();) { SearchResult sr = (SearchResult) i.next(); ch.startElement("", "result", "result", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", sr.getName()); try { addElement(ch, "fullname", sr.getNameInNamespace()); } catch (UnsupportedOperationException e) { // This seems to be the only way to know if sr contains a name! } Attributes attr = sr.getAttributes(); NamingEnumeration attrEn = attr.getAll(); while (attrEn.hasMoreElements()) { Attribute a = (Attribute) attrEn.next(); if (config.getAttributes().isEmpty() || config.getAttributes().contains(a.getID())) { ch.startElement("", "attribute", "attribute", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", a.getID()); NamingEnumeration aEn = a.getAll(); while (aEn.hasMoreElements()) { Object o = aEn.next(); addElement(ch, "value", o.toString()); } ch.endElement("", "attribute", "attribute"); } } ch.endElement("", "result", "result"); } ch.endElement("", "results", "results"); ch.endDocument(); } catch (Exception e) { throw new OXFException(e); } }