List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java
private boolean checkUsernamePassword(String username, String password, String authorizePathMode) { String dnUser = Misc.replace(ldapAuthUserBase, "%UID%", username); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapAuthUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, dnUser); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = null;//from w w w. ja v a2 s. c o m try { try { ctx = new InitialDirContext(env); } catch (CommunicationException e) { log.info("cannot create constructor for DirContext (" + e.getMessage() + "], will try again with dummy SocketFactory"); env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName()); ctx = new InitialLdapContext(env, null); } if (authorizePathMode == null) { return true; } else { if (authorizePathMode.equals(AUTH_PATH_MODE_OBSERVER)) { if (isMemberOf(ctx, dnUser, ldapAuthObserverBase)) { return true; } if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) { return true; } } if (authorizePathMode.equals(AUTH_PATH_MODE_DATAADMIN)) { if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) { return true; } } if (authorizePathMode.equals(AUTH_PATH_MODE_TESTER)) { if (isMemberOf(ctx, dnUser, ldapAuthTesterBase)) { return true; } } } } catch (AuthenticationException e) { return false; } catch (Exception e) { log.warn("LoginFilter caught Exception", e); return false; } finally { if (ctx != null) { try { ctx.close(); } catch (Exception e) { log.warn("LoginFilter caught Exception", e); } } } return false; }
From source file:org.kitodo.production.services.data.LdapServerService.java
/** * Set next free uidNumber.//from w w w . j av a 2s . c o m */ private void setNextUidNumber(LdapServer ldapServer) { Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer); DirContext ctx; try { ctx = new InitialDirContext(ldapEnvironment); Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern()); Attribute la = attrs.get("uidNumber"); String oldValue = (String) la.get(0); int bla = Integer.parseInt(oldValue) + 1; BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla)); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu); ctx.modifyAttributes(ldapServer.getNextFreeUnixIdPattern(), mods); ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * check if User already exists on system. * * @param inLogin//w ww.ja v a 2s.co m * String * @return path as string */ public boolean isUserAlreadyExists(String inLogin) { 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; boolean rueckgabe = false; try { ctx = new InitialDirContext(env); Attributes matchAttrs = new BasicAttributes(true); NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de", matchAttrs); rueckgabe = answer.hasMoreElements(); while (answer.hasMore()) { SearchResult sr = answer.next(); if (logger.isDebugEnabled()) { logger.debug(">>>" + sr.getName()); } Attributes attrs = sr.getAttributes(); String givenName = " "; String surName = " "; String mail = " "; String cn = " "; String hd = " "; try { givenName = attrs.get("givenName").toString(); } catch (Exception err) { givenName = " "; } try { surName = attrs.get("sn").toString(); } catch (Exception e2) { surName = " "; } try { mail = attrs.get("mail").toString(); } catch (Exception e3) { mail = " "; } try { cn = attrs.get("cn").toString(); } catch (Exception e4) { cn = " "; } try { hd = attrs.get("homeDirectory").toString(); } catch (Exception e4) { hd = " "; } logger.debug(givenName); logger.debug(surName); logger.debug(mail); logger.debug(cn); logger.debug(hd); } ctx.close(); } catch (NamingException e) { logger.error(e); } return rueckgabe; }
From source file:no.smint.anthropos.ldap.LDAP.java
public static PersonList retrieve() throws NamingException { Hashtable<String, Object> env = config(); DirContext ctx = new InitialDirContext(env); //Search controller SearchControls ctls = new SearchControls(); //The actual search NamingEnumeration answer = ctx.search("ou=Users,dc=studentmediene,dc=no", "(&(memberOf=*))", ctls); ctx.close();// w w w .j a v a 2s . c o m return SearchProcessing.getPersons(answer); }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Retrieve home directory of given user. * * @param user/*w w w.j ava2s . c o m*/ * User object * @return path as URI */ public URI getUserHomeDirectory(User user) { URI userFolderBasePath = URI.create("file:///" + ConfigCore.getParameter(Parameters.DIR_USERS)); if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_LOCAL_DIRECTORY)) { return userFolderBasePath.resolve(user.getLogin()); } Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) { 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(); ctx.reconnect(null); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute la = attrs.get("homeDirectory"); return URI.create((String) la.get(0)); // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return userFolderBasePath.resolve(user.getLogin()); } catch (NamingException e) { logger.error("JNDI error:", e); return userFolderBasePath.resolve(user.getLogin()); } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } } } } if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); } DirContext ctx; URI userFolderPath = null; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute ldapAttribute = attrs.get("homeDirectory"); userFolderPath = URI.create((String) ldapAttribute.get(0)); ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } if (userFolderPath != null && !userFolderPath.isAbsolute()) { if (userFolderPath.getPath().startsWith("/")) { userFolderPath = serviceManager.getFileService().deleteFirstSlashFromPath(userFolderPath); } return userFolderBasePath.resolve(userFolderPath); } else { return userFolderPath; } }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * /*from www .j av a2 s . c o m*/ * @param search * @param searchValue * @param attributeNames * @return naming enumeration */ protected NamingEnumeration getLdapResults(Search search, String searchValue, String[] attributeNames) { DirContext context = null; NamingEnumeration results = null; String filter = search.getParam("filter"); if (filter == null) { log.error("Search filter not found for search type: " + search.getSearchType()); return results; } filter = filter.replaceAll("%TERM%", escapeSearchFilter(searchValue)); String base = search.getParam("base"); if (base == null) { base = ""; log.error("Search base not found for: " + search.getSearchType() + ". Using base \"\" "); } int scopeNum = -1; String scope = search.getParam("scope"); if (scope != null) { scopeNum = getScope(scope); } if (scopeNum == -1) { scopeNum = SearchControls.SUBTREE_SCOPE; log.error("Search scope not found for: " + search.getSearchType() + ". Using scope SUBTREE_SCOPE."); } log.debug("searchType: " + search.getSearchType() + " filter: " + filter + " base: " + base + " scope: " + scope); try { context = new InitialDirContext(this.environment); SearchControls constraints = new SearchControls(); constraints.setSearchScope(scopeNum); constraints.setReturningAttributes(attributeNames); results = context.search(base, filter, constraints); } catch (AuthenticationException ex) { log.error("Ldap Authentication Exception: " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("Ldap NamingException: " + ex.getMessage(), ex); } finally { if (context != null) { try { context.close(); } catch (NamingException ne) { // squelch, since it is already closed } } } return results; }
From source file:org.apache.syncope.core.rest.AbstractTest.java
@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" }) protected Object getLdapRemoteObject(final String bindDn, final String bindPwd, final String objectDn) { ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP); final Map<String, ConnConfProperty> ldapConnConf = connectorService.read(ldapRes.getConnectorId()) .getConfigurationMap();/*from w ww . j a va 2 s . c o m*/ Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + ldapConnConf.get("host").getValues().get(0) + ":" + ldapConnConf.get("port").getValues().get(0) + "/"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDn == null ? ldapConnConf.get("principal").getValues().get(0) : bindDn); env.put(Context.SECURITY_CREDENTIALS, bindPwd == null ? ldapConnConf.get("credentials").getValues().get(0) : bindPwd); try { final InitialDirContext ctx = new InitialDirContext(env); return ctx.lookup(objectDn); } catch (Exception e) { return null; } }
From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java
@Test public void testRunning() throws Exception { 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, "simple"); env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL); env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS); DirContext ctx = new InitialDirContext(env); HashSet<String> set = new HashSet<>(); NamingEnumeration<NameClassPair> list = ctx.list("ou=system"); while (list.hasMore()) { NameClassPair ncp = list.next(); set.add(ncp.getName());// ww w . j ava2s .co m } Assert.assertTrue(set.contains("uid=admin")); Assert.assertTrue(set.contains("ou=users")); Assert.assertTrue(set.contains("ou=groups")); Assert.assertTrue(set.contains("ou=configuration")); Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot")); ctx.close(); }
From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java
private NamingEnumeration getBasicNamingEnumeration(String userid, String password, String filter, SearchControls searchControls, Hashtable env) throws NamingException, Exception { String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getNamingEnumeration() "; log.debug(m + ">"); NamingEnumeration ne = null;// w ww .j a v a2s .c om try { DirContext ctx; try { ctx = new InitialDirContext(env); } catch (NamingException th) { String msg = "exception getting ldap context"; if (LOG_STACK_TRACES) { log.error(m + msg, th); } else { log.error(m + msg + " " + th.getMessage()); } throw th; } if (ctx == null) { log.error(m + "unexpected null ldap context"); throw new NamingException(""); } try { ne = ctx.search(BASE, filter, searchControls); } catch (NamingException th) { String msg = "exception getting ldap enumeration"; if (LOG_STACK_TRACES) { log.error(m + msg, th); } else { log.error(m + msg + " " + th.getMessage()); } throw th; } if (ne == null) { log.error(m + "unexpected null ldap enumeration"); throw new NamingException(""); } } finally { log.debug(m + "< " + ne); } return ne; }
From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java
/** * Infer the root DN.// ww w.jav a 2 s . c om * * @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, toProviderUrl(fixNull(getServerUrl()), "")); DirContext ctx = new InitialDirContext(props); Attributes atts = ctx.getAttributes(""); Attribute a = atts.get("defaultNamingContext"); if (a != null && a.get() != null) { // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx return a.get().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; } }