List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:ldap.ActiveLoginImpl.java
/** * open the directory connection.//from www. j a v a2 s.c om * @param url * @param tracing * @return * @throws NamingException */ private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing) throws NamingException { /* * First, set up a large number of environment variables to sensible default valuse */ Hashtable env = new Hashtable(); // sanity check if (url == null) throw new NamingException("URL not specified in openContext()!"); // set the tracing level now, since it can't be set once the connection is open. if (tracing) env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output //env.put("java.naming.ldap.version", "3"); // always use ldap v3 - v2 too limited env.put(LdapConstants.ldapVersionStr, LdapConstants.ldapVersion); // always use ldap v3 - v2 too limited //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // use default jndi provider env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider //env.put("java.naming.ldap.deleteRDN", "false"); // usually what we want env.put(LdapConstants.ldapDeleteRdn, LdapConstants.ldapDeleteRdnValue); // usually what we want //env.put(Context.REFERRAL, "ignore"); //could be: follow, ignore, throw env.put(Context.REFERRAL, LdapConstants.ldapIgnore); //could be: follow, ignore, throw // env.put("java.naming.ldap.derefAliases", "finding"); // could be: finding, searching, etc. env.put(LdapConstants.ldapFindingAliases, LdapConstants.ldapFindingStr); // could be: finding, searching, etc. //env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 'simple' = username + password env.put(Context.SECURITY_AUTHENTICATION, LdapConstants.ldapSecurityAuth); // 'simple' = username + password env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string- env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389" /* * Open the actual LDAP session using the above environment variables */ DirContext newContext = new InitialDirContext(env); if (newContext == null) throw new NamingException( "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi."); return newContext; }
From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java
/** * This method retrieves data using LDAP protocol. * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com * * @param urlString/* w w w. j a v a 2 s . c o m*/ * @return */ private byte[] ldapGet(final String urlString) { final Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, urlString); try { final DirContext ctx = new InitialDirContext(env); final Attributes attributes = ctx.getAttributes(""); final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary"); final byte[] ldapBytes = (byte[]) attribute.get(); if (ldapBytes == null || ldapBytes.length == 0) { throw new DSSException("Cannot download CRL from: " + urlString); } return ldapBytes; } catch (Exception e) { LOG.warn(e.getMessage(), e); } return null; }
From source file:ru.efo.security.ADUserDetailsService.java
private DirContext getDirContext(String username, String password) throws NamingException { final Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.SECURITY_AUTHENTICATION, "simple"); props.put(Context.SECURITY_PRINCIPAL, username); props.put(Context.SECURITY_CREDENTIALS, password); props.put(Context.PROVIDER_URL, ldapUrl); props.put("java.naming.ldap.attributes.binary", "objectSID"); return new InitialDirContext(props); }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Get next free uidNumber.//from w w w . j a va 2 s .c om * * @return next free uidNumber */ private String getNextUidNumber() { Hashtable<String, String> env = getLdapConnectionSettings(); 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(ConfigCore.getParameter("ldap_nextFreeUnixId")); Attribute la = attrs.get("uidNumber"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { logger.error(e); Helper.setFehlerMeldung(e.getMessage()); } return rueckgabe; }
From source file:net.grinder.util.NetworkUtils.java
public static List<String> getDnsServers() throws NamingException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = null;//from w ww . j a va2 s. co m List<String> dnsServers = new ArrayList<String>(); try { ctx = new InitialDirContext(env); String dnsString = (String) ctx.getEnvironment().get("java.naming.provider.url"); for (String each : dnsString.split(" ")) { dnsServers.add(each.replace("dns://", "")); } } catch (Exception e) { NoOp.noOp(); } finally { if (ctx != null) { ctx.close(); } } return dnsServers; }
From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java
@Test public void testSaslGssapiLdapAuth() throws Exception { final Hashtable<String, String> env = new Hashtable<>(); env.put(Context.PROVIDER_URL, "ldap://localhost:1024"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI"); LoginContext loginContext = new LoginContext("broker-sasl-gssapi"); loginContext.login();// w w w. j a va2s. c o m try { Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> { HashSet<String> set = new HashSet<>(); DirContext ctx = new InitialDirContext(env); NamingEnumeration<NameClassPair> list = ctx.list("ou=system"); while (list.hasMore()) { NameClassPair ncp = list.next(); set.add(ncp.getName()); } Assert.assertTrue(set.contains("uid=first")); Assert.assertTrue(set.contains("cn=users")); Assert.assertTrue(set.contains("ou=configuration")); Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot")); ctx.close(); return null; }); } catch (PrivilegedActionException e) { throw e.getException(); } }
From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Bind authenticate.//from w w w .j av a 2 s . c o m * * @param username the user to be used * @param password the password to be used * @return true if the user was authenticated * @throws PortalServiceException for any errors encountered */ public boolean authenticate(String username, String password) throws PortalServiceException { DirContext ctx = null; try { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, env.getProperty(Context.INITIAL_CONTEXT_FACTORY)); props.put(Context.PROVIDER_URL, env.getProperty(Context.PROVIDER_URL)); props.put(Context.SECURITY_PRINCIPAL, MessageFormat.format(userDNPattern, username)); props.put(Context.SECURITY_CREDENTIALS, password); ctx = new InitialDirContext(props); return true; } catch (AuthenticationException authEx) { return false; } catch (NamingException e) { throw new PortalServiceException("Could not verify authentication results.", e); } finally { closeContext(ctx); } }
From source file:org.kitodo.production.services.data.LdapServerService.java
/** * change password of given user, needs old password for authentication. * * @param user/* ww w .j a v a2 s .co m*/ * User object * @param inNewPassword * String * @return boolean about result of change */ public boolean changeUserPassword(User user, String inNewPassword) throws NoSuchAlgorithmException { JDKMessageDigest.MD4 digester = new JDKMessageDigest.MD4(); PasswordEncryption passwordEncryption = user.getLdapGroup().getLdapServer().getPasswordEncryption(); Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); if (!user.getLdapGroup().getLdapServer().isReadOnly()) { try { ModificationItem[] mods = new ModificationItem[4]; // encryption of password and Base64-Encoding MessageDigest md = MessageDigest.getInstance(passwordEncryption.getTitle()); md.update(inNewPassword.getBytes(StandardCharsets.UTF_8)); String encryptedPassword = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8); // change attribute userPassword BasicAttribute userPassword = new BasicAttribute("userPassword", "{" + passwordEncryption + "}" + encryptedPassword); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword); // change attribute lanmgrPassword BasicAttribute lanmgrPassword = proceedPassword("sambaLMPassword", inNewPassword, null); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrPassword); // change attribute ntlmPassword BasicAttribute ntlmPassword = proceedPassword("sambaNTPassword", inNewPassword, digester); mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmPassword); BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet", String.valueOf(System.currentTimeMillis() / 1000L)); mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet); DirContext ctx = new InitialDirContext(env); ctx.modifyAttributes(buildUserDN(user), mods); // Close the context when we're done ctx.close(); return true; } catch (NamingException e) { logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e); return false; } } return false; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java
protected InitialDirContext buildInitialDirContext(final Map<String, String> config, final int pageSize, final AuthenticationDiagnostic diagnostic) throws AuthenticationException { final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic : new AuthenticationDiagnostic(); final String securityPrincipal = config.get(Context.SECURITY_PRINCIPAL); final String providerURL = config.get(Context.PROVIDER_URL); if (this.isSSLSocketFactoryRequired(config)) { final KeyStore trustStore = this.initTrustStore(); ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName()); }/* w ww.j av a 2s . c o m*/ try { // If a page size has been requested, use LDAP v3 paging if (pageSize > 0) { final InitialLdapContext ctx = new InitialLdapContext(new Hashtable<>(config), null); ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) }); return ctx; } else { final InitialDirContext ret = new InitialDirContext(new Hashtable<>(config)); final Object[] args = { providerURL, securityPrincipal }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); return ret; } } catch (final javax.naming.AuthenticationException ax) { final Object[] args1 = { securityPrincipal }; final Object[] args = { providerURL, securityPrincipal }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1); // wrong user/password - if we get this far the connection is O.K final Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.authentication", effectiveDiagnostic, args2, ax); } catch (final CommunicationException ce) { final Object[] args1 = { providerURL }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1); final StringBuffer message = new StringBuffer(); message.append(ce.getClass().getName() + ", " + ce.getMessage()); Throwable cause = ce.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect final Object[] args = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.communication", effectiveDiagnostic, args, ce); } catch (final NamingException nx) { final Object[] args = { providerURL }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args); final StringBuffer message = new StringBuffer(); message.append(nx.getClass().getName() + ", " + nx.getMessage()); Throwable cause = nx.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect final Object[] args1 = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.connection", effectiveDiagnostic, args1, nx); } catch (final IOException e) { final Object[] args = { providerURL, securityPrincipal }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); throw new AuthenticationException("Unable to encode LDAP v3 request controls", e); } }
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;// w ww .j a v a2s. c om } 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); } }