List of usage examples for javax.naming.ldap InitialLdapContext InitialLdapContext
@SuppressWarnings("unchecked") public InitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException
From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java
/** {@inheritDoc} */ public void init(FilterConfig filterConfig) throws ServletException { ServletContext context = filterConfig.getServletContext(); contextPath = context.getContextPath(); Configuration conf = new Configuration(false); conf.addResource("hdfsproxy-default.xml"); conf.addResource("hdfsproxy-site.xml"); // extract namenode from source conf. String nn = getNamenode(conf); InetSocketAddress nAddr = NetUtils.createSocketAddr(nn); context.setAttribute("name.node.address", nAddr); context.setAttribute("name.conf", conf); context.setAttribute(JspHelper.CURRENT_CONF, conf); // for storing hostname <--> cluster mapping to decide which source cluster // to forward context.setAttribute("org.apache.hadoop.hdfsproxy.conf", conf); if (lctx == null) { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(InitialLdapContext.INITIAL_CONTEXT_FACTORY, conf.get("hdfsproxy.ldap.initial.context.factory", "com.sun.jndi.ldap.LdapCtxFactory")); env.put(InitialLdapContext.PROVIDER_URL, conf.get("hdfsproxy.ldap.provider.url")); try {/*from w w w . j a va2 s. c om*/ lctx = new InitialLdapContext(env, null); } catch (NamingException ne) { throw new ServletException("NamingException in initializing ldap" + ne.toString()); } baseName = conf.get("hdfsproxy.ldap.role.base"); hdfsIpSchemaStr = conf.get("hdfsproxy.ldap.ip.schema.string", "uniqueMember"); hdfsIpSchemaStrPrefix = conf.get("hdfsproxy.ldap.ip.schema.string.prefix", "cn="); hdfsUidSchemaStr = conf.get("hdfsproxy.ldap.uid.schema.string", "uid"); hdfsPathSchemaStr = conf.get("hdfsproxy.ldap.hdfs.path.schema.string", "documentLocation"); } LOG.info(contextPath + ":: LdapIpDirFilter initialization successful"); }
From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java
private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException { LdapContext ctx = null;// w w w . j a v a 2 s .c o 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, providerUrl); try { // Create initial context ctx = new InitialLdapContext(env, null); // Establish TLS session StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); if (disableHostNameVerification) { tls.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } tls.negotiate(); // Initialize security credentials & perform read operation for // verification. ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); ctx.lookup(userDN); logger.debug("Authentication successful for {}", userDN); } catch (NamingException | IOException ex) { throw new AuthenticationException("Error validating LDAP user", ex); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { /* Ignore. */ } } } }
From source file:org.apache.jackrabbit.oak.security.authentication.ldap.AbstractServer.java
/** * Common code to get an initial context via a simple bind to the * server over the wire using the SUN JNDI LDAP provider. Do not use * this method until after the setUp() method is called to start the * server otherwise it will fail./*from ww w . j a v a2 s . c om*/ * * @param bindPrincipalDn the DN of the principal to bind as * @param password the password of the bind principal * @return an LDAP context as the the administrator to the rootDSE * @throws NamingException if the server cannot be contacted */ protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY); env.put(Context.PROVIDER_URL, "ldap://localhost:" + port); env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, "simple"); return new InitialLdapContext(env, null); }
From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
/** * Answers a new LDAP/JNDI context using the specified user credentials. * * @return an LDAP directory context/* w w w .j a va2 s . c om*/ * @throws NamingException * Propagated from underlying LDAP communication API. */ protected LdapContext computeLdapContext() throws NamingException { return new RetryingLdapContext(schedule, maxRetries, log) { @Override public Context newDelegate() throws NamingException { return new InitialLdapContext(getContextEnvironment(), null); } }; }
From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java
public void init(String url) throws NamingException, ConfigurationException { env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration() .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory")); env.put(Context.SECURITY_AUTHENTICATION, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple")); env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389 this.url = url; try {//from ww w. j a v a 2s . co m ctx = new InitialLdapContext(env, null); } catch (NamingException e) { logger.error("Naming exception " + e); throw e; } }
From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java
public String authenticate(String authorizedName, String cred) throws AuthenticationException, FatalErrorException { if (authorizedName == null || "".equals(authorizedName)) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); }//w w w .ja v a2s . c o m boolean isLdapUser = false; int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; try { MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; logger.error("config exception! " + authorizedName, ex); } try { env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration() .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory")); env.put(Context.SECURITY_AUTHENTICATION, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple")); env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389 String format = String.format( AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_LDAP_EXPANDED_STR), authorizedName); env.put(Context.SECURITY_PRINCIPAL, format); env.put(Context.SECURITY_CREDENTIALS, cred); ctx = new InitialLdapContext(env, null); isLdapUser = true; logger.info(authorizedName + " is authenticated"); } catch (ConfigurationException e) { logger.error(authorizedName + " is not authenticated", e); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } catch (NamingException e) { logger.error(authorizedName + " is not authenticated"); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } finally { try { ctx.close(); } catch (NamingException e) { logger.error("Context close failure " + e); } } if (isLdapUser) { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) { logger.warn("Publisher was not found, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(authorizedName); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } else { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } return authorizedName; }
From source file:org.apache.juddi.v3.auth.LdapSimpleAuthenticator.java
public String authenticate(String authorizedName, String cred) throws AuthenticationException, FatalErrorException { if (authorizedName == null || "".equals(authorizedName)) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); }/*from w w w .j a v a 2s .c o m*/ int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; try { MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; logger.error("config exception! " + authorizedName, ex); } boolean isLdapUser = false; try { env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration() .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory")); env.put(Context.SECURITY_AUTHENTICATION, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple")); env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389 env.put(Context.SECURITY_PRINCIPAL, authorizedName); env.put(Context.SECURITY_CREDENTIALS, cred); ctx = new InitialLdapContext(env, null); isLdapUser = true; logger.info(authorizedName + " is authenticated"); } catch (ConfigurationException e) { logger.error(authorizedName + " is not authenticated", e); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } catch (NamingException e) { logger.error(authorizedName + " is not authenticated"); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } finally { try { ctx.close(); } catch (NamingException e) { logger.error("Context close failure " + e); } } if (isLdapUser) { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) { logger.warn("Publisher was not found, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(authorizedName); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } else { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } return authorizedName; }
From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java
/** * Find account by account name.//w w w. j av a 2 s .c o m * * @param accountName the account name * @return the search result * @throws NamingException the naming exception */ protected SearchResult findAccountByAccountName(String accountName) throws NamingException { String searchFilter = String.format(searchFilterPattern, accountName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); InitialLdapContext ctx = new InitialLdapContext(env, null); try { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls); if (!results.hasMoreElements()) { throw new UserConfigLoaderException("LDAP Search returned no accounts"); } SearchResult searchResult = results.nextElement(); if (results.hasMoreElements()) { throw new UserConfigLoaderException("More than one account found in ldap search"); } return searchResult; } finally { ctx.close(); } }
From source file:org.apache.ranger.ldapconfigcheck.LdapConfigCheckMain.java
public static void main(String[] args) { CommandLineOptions cli = new CommandLineOptions(args); cli.parse();/*from w w w . java 2s. c o m*/ String inFileName = cli.getInput(); String outputDir = cli.getOutput(); if (!outputDir.endsWith("/")) { outputDir = outputDir.concat("/"); } LdapConfig config = new LdapConfig(inFileName, cli.getBindPassword()); if (cli.getLdapUrl() != null && !cli.getLdapUrl().isEmpty()) { config.updateInputPropFile(cli.getLdapUrl(), cli.getBindDn(), cli.getBindPassword(), cli.getUserSearchBase(), cli.getUserSearchFilter(), cli.getAuthUser(), cli.getAuthPass()); } PrintStream logFile = null; PrintStream ambariProps = null; PrintStream installProps = null; LdapContext ldapContext = null; try { logFile = new PrintStream(new File(outputDir + LOG_FILE)); ambariProps = new PrintStream(new File(outputDir + AMBARI_PROPERTIES)); installProps = new PrintStream(new File(outputDir + INSTALL_PROPERTIES)); UserSync userSyncObj = new UserSync(config, logFile, ambariProps, installProps); String bindDn = config.getLdapBindDn(); Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, config.getLdapUrl()); env.put(Context.SECURITY_PRINCIPAL, bindDn); env.put(Context.SECURITY_CREDENTIALS, cli.getBindPassword()); env.put(Context.SECURITY_AUTHENTICATION, config.getLdapAuthenticationMechanism()); env.put(Context.REFERRAL, "follow"); ldapContext = new InitialLdapContext(env, null); if (config.isPagedResultsEnabled()) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(config.getPagedResultsSize(), Control.CRITICAL) }); } String retrieveValues = "all"; if (cli.getDiscoverProperties() != null) { retrieveValues = cli.getDiscoverProperties(); if (cli.getDiscoverProperties().equalsIgnoreCase("users")) { userSyncObj.findUserProperties(ldapContext); } else if (cli.getDiscoverProperties().equalsIgnoreCase("groups")) { userSyncObj.findGroupProperties(ldapContext); } else { findAllUserSyncProperties(ldapContext, userSyncObj); } } else if (cli.getRetrieveValues() != null) { retrieveValues = cli.getRetrieveValues(); } else { cli.help(); } if (cli.isAuthEnabled()) { authenticate(userSyncObj, config, logFile, ambariProps, installProps); } retrieveUsersGroups(ldapContext, userSyncObj, retrieveValues); if (ldapContext != null) { ldapContext.close(); } } catch (FileNotFoundException fe) { System.out.println(fe.getMessage()); } catch (IOException ioe) { logFile.println("ERROR: Failed while setting the paged results controls\n" + ioe); } catch (NamingException ne) { System.out.println("ERROR: Failed to perfom ldap bind. Please verify values for " + "ranger.usersync.ldap.binddn and ranger.usersync.ldap.ldapbindpassword\n" + ne); } catch (Throwable t) { if (logFile != null) { logFile.println("ERROR: Connection failed: " + t.getMessage()); } else { System.out.println("ERROR: Connection failed: " + t.getMessage()); } } finally { if (logFile != null) { logFile.close(); } if (ambariProps != null) { ambariProps.close(); } if (installProps != null) { installProps.close(); } try { if (ldapContext != null) { ldapContext.close(); } } catch (NamingException ne) { System.out.println("Failed to close LdapContext!"); } } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void createLdapContext() throws Throwable { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); if (ldapUrl.startsWith("ldaps") && (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty())) { env.put("java.naming.ldap.factory.socket", "org.apache.ranger.ldapusersync.process.CustomSSLSocketFactory"); }//from www .jav a2 s .c om ldapContext = new InitialLdapContext(env, null); if (!ldapUrl.startsWith("ldaps")) { if (config.isStartTlsEnabled()) { tls = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest()); if (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty()) { tls.negotiate(CustomSSLSocketFactory.getDefault()); } else { tls.negotiate(); } LOG.info("Starting TLS session..."); } } ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, ldapBindDn); ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, ldapBindPassword); ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism); ldapContext.addToEnvironment(Context.REFERRAL, ldapReferral); }