List of usage examples for javax.naming.ldap LdapContext close
public void close() throws NamingException;
From source file:com.wfp.utils.LDAPUtils.java
/** * Overloaded method used to search the ldap based on the search constraints, search filter & search base * @param attrs/*from w w w. jav a 2s . co m*/ * @param searchFilter * @param searchBase * @return * @throws NamingException */ @SuppressWarnings("unchecked") public static NamingEnumeration getSearchResults(String[] attrs, String searchFilter, String searchBase) { LdapContext ldapCtx = null; try { try { ldapCtx = getLDAPContext(); } catch (NamingException e) { Logger.error("Error occured while creating the connection to LDAP[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } if (ldapCtx == null) { return null; } SearchControls searchCtls = getSimpleSearchControls(attrs); // Search for objects using the filter try { return ldapCtx.search(searchBase, searchFilter, searchCtls); } catch (NamingException e) { Logger.error( "Error occured while searching results :288: getSearchResults(String[] attrs, String searchFilter, String searchBase): [" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } finally { if (ldapCtx != null) { try { ldapCtx.close(); } catch (NamingException e) { Logger.error("Error occured while closing connection to LDAP [" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } } return null; }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will return the LDAP schema associated with the supplied dn. The * resulting <code>Iterator</code> is a deep copy of the original search * results. See {@link javax.naming.DirContext#getSchema(String)}. * * @param dn <code>String</code> named object in the LDAP * * @return <code>Iterator</code> - LDAP search result * * @throws NamingException if the LDAP returns an error *///w ww . j a v a 2 s .c om protected Iterator<SearchResult> getSchema(final String dn) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("Schema search with the following parameters:"); this.logger.debug(" dn = " + dn); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<SearchResult> results = null; LdapContext ctx = null; DirContext schema = null; NamingEnumeration<SearchResult> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); schema = ctx.getSchema(dn); en = schema.search("", null); results = SR_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (schema != null) { schema.close(); } if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }
From source file:com.aurel.track.util.LdapUtil.java
static TPersonBean getLdapUser(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String searchStr) throws Exception { LdapContext ctx = null; try {//from w w w . jav a2 s . c o m ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { LOGGER.warn("The context is null"); } // Control the search SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Don't ask for more than we can handle anyways if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return null; } String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME); String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME); String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL); String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE); NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); return getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); } } catch (NamingException e) { LOGGER.warn( "Searching from " + providerUrl + " by filter " + searchStr + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } finally { if (ctx != null) { ctx.close(); } } return null; }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will return the matching attributes associated with the supplied dn. * If retAttrs is null then all attributes will be returned. If retAttrs is an * empty array then no attributes will be returned. See {@link * javax.naming.DirContext#getAttributes(String, String[])}. * * @param dn <code>String</code> named object in the LDAP * @param retAttrs <code>String[]</code> attributes to return * @param handler <code>AttributeHandler[]</code> to post process results * * @return <code>Attributes</code> * * @throws NamingException if the LDAP returns an error *//*w w w .ja v a2s .com*/ protected Attributes getAttributes(final String dn, final String[] retAttrs, final AttributeHandler... handler) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("Attribute search with the following parameters:"); this.logger.debug(" dn = " + dn); this.logger.debug(" retAttrs = " + (retAttrs == null ? "all attributes" : Arrays.toString(retAttrs))); this.logger.debug(" handler = " + Arrays.toString(handler)); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } LdapContext ctx = null; Attributes attrs = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); attrs = ctx.getAttributes(dn, retAttrs); if (handler != null && handler.length > 0) { final SearchCriteria sc = new SearchCriteria(); if (ctx != null && !"".equals(ctx.getNameInNamespace())) { sc.setDn(ctx.getNameInNamespace()); } else { sc.setDn(dn); } for (int j = 0; j < handler.length; j++) { attrs = AttributesProcessor.executeHandler(sc, attrs, handler[j], this.config.getHandlerIgnoreExceptions()); } } break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (ctx != null) { ctx.close(); } } return attrs; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Check if connection with login and password possible. * * @param inBenutzer/*from ww w . ja v a 2 s .co m*/ * User object * @param inPasswort * String * @return Login correct or not */ public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) { logger.debug("start login session with ldap"); Hashtable<String, String> env = getLdapConnectionSettings(); // Start TLS if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) { logger.debug("use TLS for auth"); env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url")); env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null; try { ctx = new InitialLdapContext(env, null); // Authentication must be performed over a secure channel tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tls.negotiate(); // Authenticate via SASL EXTERNAL mechanism using client X.509 // certificate contained in JVM keystore ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer)); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort); ctx.reconnect(null); return true; // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return false; } catch (NamingException e) { logger.error("JNDI error:", e); return false; } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e); } } } } else { logger.debug("don't use TLS for auth"); if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); // TODO auf passwort testen } else { env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer)); env.put(Context.SECURITY_CREDENTIALS, inPasswort); } logger.debug("ldap environment set"); try { if (logger.isDebugEnabled()) { logger.debug("start classic ldap authentification"); logger.debug("user DN is " + getUserDN(inBenutzer)); } if (ConfigCore.getParameter("ldap_AttributeToTest") == null) { logger.debug("ldap attribute to test is null"); DirContext ctx = new InitialDirContext(env); ctx.close(); return true; } else { logger.debug("ldap attribute to test is not null"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest")); logger.debug("ldap attributes set"); String test = (String) la.get(0); if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) { logger.debug("ldap ok"); ctx.close(); return true; } else { logger.debug("ldap not ok"); ctx.close(); return false; } } } catch (NamingException e) { if (logger.isDebugEnabled()) { logger.debug("login not allowed for " + inBenutzer.getLogin(), e); } return false; } } }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * retrieve home directory of given user. * * @param inBenutzer//from w w w . j a va 2 s . co m * User object * @return path as string */ public String getUserHomeDirectory(User inBenutzer) { if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) { return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } Hashtable<String, String> env = getLdapConnectionSettings(); if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) { env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url")); env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null; try { ctx = new InitialLdapContext(env, null); // Authentication must be performed over a secure channel tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tls.negotiate(); // Authenticate via SASL EXTERNAL mechanism using client X.509 // certificate contained in JVM keystore ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); ctx.reconnect(null); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get("homeDirectory"); return (String) la.get(0); // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } catch (NamingException e) { logger.error("JNDI error:", e); return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e); } } } } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); } else { env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); } DirContext ctx; String rueckgabe = ""; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get("homeDirectory"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { logger.error(e); } return rueckgabe; }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java
@Override public void exportUser(long userId, long userGroupId, UserOperation userOperation) throws Exception { User user = _userLocalService.getUser(userId); long companyId = user.getCompanyId(); StopWatch stopWatch = new StopWatch(); if (_log.isDebugEnabled()) { stopWatch.start();//from ww w . j a v a 2s.c om _log.debug(StringBundler.concat("Exporting user ", String.valueOf(user), " in user group ", String.valueOf(userGroupId))); } if (!_ldapSettings.isExportEnabled(companyId) || !_ldapSettings.isExportGroupEnabled(companyId)) { return; } long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress()); LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId); if (ldapContext == null) { return; } UserGroup userGroup = _userGroupLocalService.getUserGroup(userGroupId); Properties groupMappings = _ldapSettings.getGroupMappings(ldapServerId, companyId); Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId); Binding binding = _portalLDAP.getGroup(ldapServerId, companyId, userGroup.getName()); if (binding == null) { if (userOperation == UserOperation.ADD) { addGroup(ldapServerId, ldapContext, userGroup, user, groupMappings, userMappings); } else { if (_log.isWarnEnabled()) { _log.warn("Unable to get or add LDAP bindings for user group " + userGroup.getName()); } } return; } try { Name name = new CompositeName(); name.add(binding.getNameInNamespace()); Modifications modifications = _portalToLDAPConverter.getLDAPGroupModifications(ldapServerId, userGroup, user, groupMappings, userMappings, userOperation); ModificationItem[] modificationItems = modifications.getItems(); ldapContext.modifyAttributes(name, modificationItems); } catch (SchemaViolationException sve) { if (_log.isInfoEnabled()) { _log.info("Unable to update LDAP bindings for user group " + userGroup.getName(), sve); } String fullGroupDN = binding.getNameInNamespace(); Attributes attributes = _portalLDAP.getGroupAttributes(ldapServerId, companyId, ldapContext, fullGroupDN, true); Attribute groupMembers = attributes.get(groupMappings.getProperty(GroupConverterKeys.USER)); if ((groupMembers != null) && (groupMembers.size() == 1)) { ldapContext.unbind(fullGroupDN); } } finally { if (ldapContext != null) { ldapContext.close(); } if (_log.isDebugEnabled()) { _log.debug(StringBundler.concat("Finished exporting user ", String.valueOf(user), " in user group ", String.valueOf(userGroupId), " in ", String.valueOf(stopWatch.getTime()), "ms")); } } }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will query the LDAP for the supplied dn, matching attributes and * return attributes. This method will always perform a one level search. The * resulting <code>Iterator</code> is a deep copy of the original search * results. If matchAttrs is empty or null then all objects in the target * context are returned. If retAttrs is null then all attributes will be * returned. If retAttrs is an empty array then no attributes will be * returned. See {@link javax.naming.DirContext#search(String, Attributes, * String[])}.//from w w w .j a v a2 s .c o m * * @param dn <code>String</code> name to search in * @param matchAttrs <code>Attributes</code> attributes to match * @param retAttrs <code>String[]</code> attributes to return * @param handler <code>SearchResultHandler[]</code> to post process results * * @return <code>Iterator</code> - of LDAP search results * * @throws NamingException if the LDAP returns an error */ protected Iterator<SearchResult> searchAttributes(final String dn, final Attributes matchAttrs, final String[] retAttrs, final SearchResultHandler... handler) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("One level search with the following parameters:"); this.logger.debug(" dn = " + dn); this.logger.debug(" matchAttrs = " + matchAttrs); this.logger.debug(" retAttrs = " + (retAttrs == null ? "all attributes" : Arrays.toString(retAttrs))); this.logger.debug(" handler = " + Arrays.toString(handler)); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<SearchResult> results = null; LdapContext ctx = null; NamingEnumeration<SearchResult> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); en = ctx.search(dn, matchAttrs, retAttrs); if (handler != null && handler.length > 0) { final SearchCriteria sc = new SearchCriteria(); if (ctx != null && !"".equals(ctx.getNameInNamespace())) { sc.setDn(ctx.getNameInNamespace()); } else { sc.setDn(dn); } sc.setMatchAttrs(matchAttrs); sc.setReturnAttrs(retAttrs); if (handler != null && handler.length > 0) { for (int j = 0; j < handler.length; j++) { if (j == 0) { results = handler[j].process(sc, en, this.config.getHandlerIgnoreExceptions()); } else { results = handler[j].process(sc, results); } } } } else { results = SR_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); } break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will query the LDAP with the supplied dn, filter, filter arguments, * and search controls. This method will perform a search whose scope is * defined in the search controls. The resulting <code>Iterator</code> is a * deep copy of the original search results. If filterArgs is null, then no * variable substitution will occur. See {@link * javax.naming.DirContext#search( String, String, Object[], SearchControls)}. * * @param dn <code>String</code> name to begin search at * @param filter <code>String</code> expression to use for the search * @param filterArgs <code>Object[]</code> to substitute for variables in * the filter/*ww w . jav a 2 s . com*/ * @param searchControls <code>SearchControls</code> to perform search with * @param handler <code>SearchResultHandler[]</code> to post process results * * @return <code>Iterator</code> - of LDAP search results * * @throws NamingException if the LDAP returns an error */ protected Iterator<SearchResult> search(final String dn, final String filter, final Object[] filterArgs, final SearchControls searchControls, final SearchResultHandler... handler) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("Search with the following parameters:"); this.logger.debug(" dn = " + dn); this.logger.debug(" filter = " + filter); this.logger.debug(" filterArgs = " + Arrays.toString(filterArgs)); this.logger.debug(" searchControls = " + searchControls); this.logger.debug(" handler = " + Arrays.toString(handler)); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<SearchResult> results = null; LdapContext ctx = null; NamingEnumeration<SearchResult> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); en = ctx.search(dn, filter, filterArgs, searchControls); if (handler != null && handler.length > 0) { final SearchCriteria sc = new SearchCriteria(); if (ctx != null && !"".equals(ctx.getNameInNamespace())) { sc.setDn(ctx.getNameInNamespace()); } else { sc.setDn(dn); } sc.setFilter(filter); sc.setFilterArgs(filterArgs); if (searchControls != null) { sc.setReturnAttrs(searchControls.getReturningAttributes()); } for (int j = 0; j < handler.length; j++) { if (j == 0) { results = handler[j].process(sc, en, this.config.getHandlerIgnoreExceptions()); } else { results = handler[j].process(sc, results); } } } else { results = SR_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); } break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java
@Override public void importUsers(long ldapServerId, long companyId) throws Exception { if (!_ldapSettings.isImportEnabled(companyId)) { return;/*from www . j a v a 2 s . c om*/ } LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId); if (ldapContext == null) { return; } _lastImportTime = System.currentTimeMillis(); LDAPImportConfiguration ldapImportConfiguration = _ldapImportConfigurationProvider .getConfiguration(companyId); LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider .getConfiguration(companyId, ldapServerId); String[] userIgnoreAttributes = ldapServerConfiguration.userIgnoreAttributes(); Set<String> ldapUserIgnoreAttributes = new HashSet<>(Arrays.asList(userIgnoreAttributes)); try { Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId); Properties userExpandoMappings = _ldapSettings.getUserExpandoMappings(ldapServerId, companyId); Properties contactMappings = _ldapSettings.getContactMappings(ldapServerId, companyId); Properties contactExpandoMappings = _ldapSettings.getContactExpandoMappings(ldapServerId, companyId); Properties groupMappings = _ldapSettings.getGroupMappings(ldapServerId, companyId); String importMethod = ldapImportConfiguration.importMethod(); LDAPImportContext ldapImportContext = getLDAPImportContext(companyId, contactExpandoMappings, contactMappings, groupMappings, ldapContext, ldapServerId, ldapUserIgnoreAttributes, userExpandoMappings, userMappings); if (importMethod.equals(_IMPORT_BY_GROUP)) { importFromLDAPByGroup(ldapImportContext); } else if (importMethod.equals(_IMPORT_BY_USER)) { importFromLDAPByUser(ldapImportContext); } } catch (Exception e) { _log.error("Unable to import LDAP users and groups", e); } finally { ldapContext.close(); } }