List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
private DirContext getContext() { char[] rootPassword = getPassword(getTolvenConfigWrapper().getLDAPServerRootPasswordId()); if (rootPassword == null) { throw new RuntimeException( "LDAP password is null for alias: " + getTolvenConfigWrapper().getLDAPServerRootPasswordId()); }//w ww . j a v a 2s. co m Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, getProviderURL()); env.put(Context.SECURITY_PRINCIPAL, getTolvenConfigWrapper().getLDAPServerRootUser()); env.put(Context.SECURITY_CREDENTIALS, new String(rootPassword)); try { return new InitialDirContext(env); } catch (NamingException ex) { throw new RuntimeException("Could not create an IntialDirContext", ex); } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the values of the specified fields for the supplied id. * @see IExternalStorage#getFields(java.lang.String, java.util.List) *//*from ww w . j a v a 2 s.c o m*/ public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException { Hashtable<String, Object> htReturn = new Hashtable<String, Object>(); DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] saFields = fields.toArray(new String[0]); oScope.setReturningAttributes(saFields); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes '"); sbFailed.append(fields); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); htReturn.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; htReturn.put(sAttributeName, oValue); } } } catch (UserException e) { throw e; } catch (Exception e) { _logger.fatal("Could not retrieve fields: " + fields, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return htReturn; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets the initial context/*from w w w .j ava2 s . co m*/ * * @param providerUrl * @param bindDN * @param bindPassword * @return */ public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) { List<String> trace = new ArrayList<String>(); LOGGER.debug("providerURL: " + providerUrl); trace.add("Attempting to connect to the LDAP server..."); if (providerUrl != null && providerUrl.startsWith("ldaps:")) { System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE); trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE); File ks = new File(PATH_TO_KEY_STORE); if (!ks.exists()) { trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE); } } if (providerUrl == null) { LOGGER.warn("LDAP provider URL should not be null."); return null; } Hashtable<String, Object> env = new Hashtable<String, Object>(); if (LOGGER.isDebugEnabled()) { env.put("com.sun.jndi.ldape.trace.ber", System.err); } env.put("java.naming.ldap.version", "3"); env.put("com.sun.jndi.ldap.connect.timeout", "10000"); env.put("com.sun.jndi.dns.timeout.initial", "2000"); env.put("com.sun.jndi.dns.timeout.retries", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); if ((bindDN != null) && !bindDN.equals("")) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDN); env.put(Context.SECURITY_CREDENTIALS, bindPassword); LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*")); trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****"); } else { LOGGER.debug("bind anonymous"); trace.add("Preparing to bind anonymously to the LDAP server"); } try { return new InitialLdapContext(env, null); } catch (NamingException e) { for (String msg : trace) { LOGGER.error(msg); } LOGGER.error("Getting the initial ldap context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); try { new InitialDirContext(env); } catch (NamingException e1) { LOGGER.error("Getting the initial dir context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java
protected DirContext createContext() throws DirectoryException { try {//w w w .j av a 2s . c o m /* * Dynamic server list requires re-computation on each access */ String serverName = getDescriptor().getServerName(); if (StringUtils.isEmpty(serverName)) { throw new DirectoryException("server configuration is missing for directory " + getName()); } LDAPServerDescriptor serverConfig = getServer(); if (serverConfig.isDynamicServerList()) { String ldapUrls = serverConfig.getLdapUrls(); contextProperties.put(Context.PROVIDER_URL, ldapUrls); } return new InitialDirContext(contextProperties); } catch (NamingException e) { throw new DirectoryException("Cannot connect to LDAP directory '" + getName() + "': " + e.getMessage(), e); } }
From source file:hudson.security.LDAPSecurityRealm.java
/** * Infer the root DN./*from w w w . ja v a2 s . c o m*/ * * @return null if not found. */ private String inferRootDN(String server) { try { Hashtable<String, String> props = new Hashtable<String, String>(); if (managerDN != null) { props.put(Context.SECURITY_PRINCIPAL, managerDN); props.put(Context.SECURITY_CREDENTIALS, getManagerPassword()); } props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, getServerUrl() + '/'); DirContext ctx = new InitialDirContext(props); Attributes atts = ctx.getAttributes(""); Attribute a = atts.get("defaultNamingContext"); if (a != null) // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx return a.toString(); a = atts.get("namingcontexts"); if (a == null) { LOGGER.warning("namingcontexts attribute not found in root DSE of " + server); return null; } return a.get().toString(); } catch (NamingException e) { LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e); return null; } }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test case for <a href="http://issues.apache.org/jira/browse/DIREVE-284" where users in * mixed case partitions were not able to authenticate properly. This test case creates * a new partition under dc=aPache,dc=org, it then creates the example user in the JIRA * issue and attempts to authenticate as that user. * * @throws Exception if the user cannot authenticate or test fails *//*from w w w . java 2s . c om*/ @Test public void testUserAuthOnMixedCaseSuffix() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/dc=aPache,dc=org"); env.put("java.naming.ldap.version", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialDirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(""); assertTrue(attrs.get("dc").get().equals("aPache")); Attributes user = new BasicAttributes("cn", "Kate Bush", true); Attribute oc = new BasicAttribute("objectClass"); oc.add("top"); oc.add("person"); oc.add("organizationalPerson"); oc.add("inetOrgPerson"); user.put(oc); user.put("sn", "Bush"); user.put("userPassword", "Aerial"); ctx.createSubcontext("cn=Kate Bush", user); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "Aerial"); env.put(Context.SECURITY_PRINCIPAL, "cn=Kate Bush,dc=aPache,dc=org"); InitialDirContext userCtx = new InitialDirContext(env); assertNotNull(userCtx); ctx.destroySubcontext("cn=Kate Bush"); }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * retrieve home directory of given user. * * @param inBenutzer/*from www . j a v a2 s .c o 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:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java
public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse, LDAPResolver ldapResolver) throws PIPException { /*//from w ww . j a v a2 s . c o m * Check with the resolver to get the base string */ String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder); if (stringBase == null) { this.logger.warn(this.getName() + " does not handle " + pipRequest.toString()); return; } /* * Get the filter string */ String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder); /* * Check the cache */ Cache<String, PIPResponse> cache = this.getCache(); String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter); if (cache != null) { PIPResponse pipResponse = cache.getIfPresent(cacheKey); if (pipResponse != null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Returning cached response: " + pipResponse); } mutablePIPResponse.addAttributes(pipResponse.getAttributes()); return; } } /* * Not in the cache, so set up the LDAP query session */ DirContext dirContext = null; PIPResponse pipResponse = null; try { /* * Create the DirContext */ dirContext = new InitialDirContext(this.ldapEnvironment); /* * Set up the search controls */ SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(this.ldapScope); /* * Do the search */ NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter, searchControls); if (namingEnumeration != null && namingEnumeration.hasMore()) { while (namingEnumeration.hasMore()) { List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next()); if (listAttributes != null && listAttributes.size() > 0) { mutablePIPResponse.addAttributes(listAttributes); } } } /* * Put in the cache */ if (cache != null) { cache.put(cacheKey, pipResponse); } } catch (NamingException ex) { this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex); } finally { if (dirContext != null) { try { dirContext.close(); } catch (Exception ex) { this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex); } } } }
From source file:org.kitodo.production.services.data.LdapServerService.java
/** * Get next free uidNumber.//from w w w . j a va2 s.c o m * * @return next free uidNumber */ private String getNextUidNumber(LdapServer ldapServer) { Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer); DirContext ctx; String rueckgabe = ""; try { ctx = new InitialDirContext(ldapEnvironment); Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern()); Attribute la = attrs.get("uidNumber"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { Helper.setErrorMessage(e.getMessage(), logger, e); } return rueckgabe; }
From source file:org.apache.hadoop.security.LdapGroupsMapping.java
DirContext getDirContext() throws NamingException { if (ctx == null) { // Set up the initial environment for LDAP connectivity Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.ldap.LdapCtxFactory.class.getName()); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); // Set up SSL security, if necessary if (useSsl) { env.put(Context.SECURITY_PROTOCOL, "ssl"); System.setProperty("javax.net.ssl.keyStore", keystore); System.setProperty("javax.net.ssl.keyStorePassword", keystorePass); }/* w w w. j a v a2s. co m*/ env.put(Context.SECURITY_PRINCIPAL, bindUser); env.put(Context.SECURITY_CREDENTIALS, bindPassword); env.put("com.sun.jndi.ldap.connect.timeout", conf.get(CONNECTION_TIMEOUT, String.valueOf(CONNECTION_TIMEOUT_DEFAULT))); env.put("com.sun.jndi.ldap.read.timeout", conf.get(READ_TIMEOUT, String.valueOf(READ_TIMEOUT_DEFAULT))); ctx = new InitialDirContext(env); } return ctx; }