javax.naming.directory.InitialDirContext Java Examples
The following examples show how to use
javax.naming.directory.InitialDirContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ThirdEyeLdapAuthenticator.java From incubator-pinot with Apache License 2.0 | 6 votes |
/** * Tries to authenticate with the given authentication environment and store the result to the given container of * authentication results. * * @param authEnv the table that contains the authentication information. * * @return authenticationResults the container for the result. */ private AuthenticationResult authenticate(Hashtable<String, String> authEnv) { AuthenticationResult authenticationResult = new AuthenticationResult(); try { new InitialDirContext(authEnv).close(); authenticationResult.setAuthenticated(true); authenticationResult.setMessage( String.format("Successfully authenticated '%s' with LDAP", authEnv.get(Context.SECURITY_PRINCIPAL))); } catch (NamingException e) { authenticationResult.setAuthenticated(false); authenticationResult.setMessage( String.format("Failed to authenticate '%s' with LDAP: %s", authEnv.get(Context.SECURITY_PRINCIPAL), e.getMessage())); } return authenticationResult; }
Example #2
Source File: NamingExceptionTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@Test public void testNamingExceptionWithNonSerializableResolvedObj() throws Exception { javax.naming.NameAlreadyBoundException wrappedException = new javax.naming.NameAlreadyBoundException( "some error"); wrappedException.setResolvedObj(new InitialDirContext()); NamingException exception = new NameAlreadyBoundException( wrappedException); writeToStream(exception); NamingException deSerializedException = readFromStream(); assertNotNull( "Original exception resolvedObj after serialization should not be null", exception.getResolvedObj()); assertNull("De-serialized exception resolvedObj should be null", deSerializedException.getResolvedObj()); }
Example #3
Source File: EtcdClientAutoConfiguration.java From spring-boot-etcd with MIT License | 6 votes |
private List<String> discoverNodes(String serviceName) throws NamingException { List<String> locations = new ArrayList<>(); Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); env.put("java.naming.provider.url", "dns:"); DirContext context = new InitialDirContext(env); Attributes attributes = context.getAttributes(serviceName, new String[] { "SRV" }); for (NamingEnumeration<? extends Attribute> records = attributes.getAll(); records.hasMore();) { Attribute record = records.next(); NamingEnumeration<String> values = (NamingEnumeration<String>) record.getAll(); while (values.hasMore()) { String dns = values.next(); String[] split = dns.split(" "); String host = split[3]; if (host.endsWith(".")) { host = host.substring(0, host.length() - 1); } String location = "http://" + host + ":2379"; locations.add(location); } } return locations; }
Example #4
Source File: SchemaToJava.java From spring-ldap with Apache License 2.0 | 6 votes |
private static ObjectSchema readSchema(String url, String user, String pass, SyntaxToJavaClass syntaxToJavaClass, Set<String> binarySet, Set<String> objectClasses) throws NamingException, ClassNotFoundException { // Set up environment Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.PROVIDER_URL, url); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); if (user != null) { env.put(Context.SECURITY_PRINCIPAL, user); } if (pass != null) { env.put(Context.SECURITY_CREDENTIALS, pass); } DirContext context = new InitialDirContext(env); DirContext schemaContext = context.getSchema(""); SchemaReader reader = new SchemaReader(schemaContext, syntaxToJavaClass, binarySet); ObjectSchema schema = reader.getObjectSchema(objectClasses); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Schema - %1$s", schema.toString())); } return schema; }
Example #5
Source File: XAJNDITest.java From spliceengine with GNU Affero General Public License v3.0 | 6 votes |
private InitialDirContext getInitialDirContext() { try { Hashtable env = new Hashtable(); // using properties - these will have been passed in. String ldapContextFactory=getSystemProperty("derbyTesting.ldapContextFactory"); if (ldapContextFactory == null || ldapContextFactory.length() < 1) env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); else env.put(Context.INITIAL_CONTEXT_FACTORY, ldapContextFactory); env.put(Context.PROVIDER_URL, "ldap://" + ldapServer + ":" + ldapPort); env.put(Context.SECURITY_AUTHENTICATION, "simple"); return new InitialDirContext(env); } catch (NamingException ne) { fail("naming exception "); return null; } }
Example #6
Source File: LdapExternalUidLookup.java From unitime with Apache License 2.0 | 6 votes |
public DirContext getDirContext() throws NamingException { Hashtable<String,String> env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory")); env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider")); env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore")); if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null) env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")); env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple")); if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null) env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")); if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null) System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath())); if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null) System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath())); if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null) System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword")); if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null) System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")); if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null) System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")); return new InitialDirContext(env); }
Example #7
Source File: QuarkusDirContextFactory.java From quarkus with Apache License 2.0 | 6 votes |
@Override public void returnContext(DirContext context) { if (context == null) { return; } if (context instanceof InitialDirContext) { final ClassLoader oldClassLoader = setClassLoaderTo(targetClassLoader); try { context.close(); // log.debugf("Context [%s] was closed. Connection closed or just returned to the pool.", context); } catch (NamingException ignored) { } finally { setClassLoaderTo(oldClassLoader); } } }
Example #8
Source File: LdapManager.java From fess with Apache License 2.0 | 6 votes |
protected DirContextHolder getDirContext(final Supplier<Hashtable<String, String>> envSupplier) { DirContextHolder holder = contextLocal.get(); if (holder == null) { final Hashtable<String, String> env = envSupplier.get(); try { holder = new DirContextHolder(new InitialDirContext(env)); contextLocal.set(holder); return holder; } catch (final NamingException e) { throw new LdapOperationException("Failed to create DirContext.", e); } } else { holder.inc(); return holder; } }
Example #9
Source File: ScoreCommand.java From AntiVPN with MIT License | 6 votes |
private static Set<String> collectRecords(String dns) { if (ConfigUtil.getDebugOrFalse()) { logger.info("Collecting A records for " + dns); } Set<String> retVal = new HashSet<>(); try { InitialDirContext context = new InitialDirContext(); Attributes attributes = context.getAttributes("dns:/" + dns, new String[] { "A" }); NamingEnumeration<?> attributeEnum = attributes.get("A").getAll(); while (attributeEnum.hasMore()) { retVal.add(attributeEnum.next().toString()); } } catch (NamingException ex) { logger.error(ex.getMessage(), ex); } if (ConfigUtil.getDebugOrFalse()) { logger.info("Got " + retVal.size() + " record(s) for " + dns); } return retVal; }
Example #10
Source File: ScoreCommand.java From AntiVPN with MIT License | 6 votes |
private static Set<String> collectRecords(String dns) { if (ConfigUtil.getDebugOrFalse()) { logger.info("Collecting A records for " + dns); } Set<String> retVal = new HashSet<>(); try { InitialDirContext context = new InitialDirContext(); Attributes attributes = context.getAttributes("dns:/" + dns, new String[] { "A" }); NamingEnumeration<?> attributeEnum = attributes.get("A").getAll(); while (attributeEnum.hasMore()) { retVal.add(attributeEnum.next().toString()); } } catch (NamingException ex) { logger.error(ex.getMessage(), ex); } if (ConfigUtil.getDebugOrFalse()) { logger.info("Got " + retVal.size() + " record(s) for " + dns); } return retVal; }
Example #11
Source File: ScoreCommand.java From AntiVPN with MIT License | 6 votes |
private static Set<String> collectRecords(String dns) { if (ConfigUtil.getDebugOrFalse()) { logger.info("Collecting A records for " + dns); } Set<String> retVal = new HashSet<>(); try { InitialDirContext context = new InitialDirContext(); Attributes attributes = context.getAttributes("dns:/" + dns, new String[] { "A" }); NamingEnumeration<?> attributeEnum = attributes.get("A").getAll(); while (attributeEnum.hasMore()) { retVal.add(attributeEnum.next().toString()); } } catch (NamingException ex) { logger.error(ex.getMessage(), ex); } if (ConfigUtil.getDebugOrFalse()) { logger.info("Got " + retVal.size() + " record(s) for " + dns); } return retVal; }
Example #12
Source File: LegacyLDAPSecuritySettingPluginTest2.java From activemq-artemis with Apache License 2.0 | 6 votes |
@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()); } 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")); }
Example #13
Source File: ServerPinger.java From FishingBot with GNU General Public License v3.0 | 6 votes |
/** * Returns a server's address and port for the specified hostname, looking up the SRV record if possible * Copied from Minecraft src */ private static String[] getServerAddress(String serverHost) { try { Class.forName("com.sun.jndi.dns.DnsContextFactory"); Hashtable<String, String> hashtable = new Hashtable<>(); hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); hashtable.put("java.naming.provider.url", "dns:"); hashtable.put("com.sun.jndi.dns.timeout.retries", "1"); DirContext dircontext = new InitialDirContext(hashtable); Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + serverHost, new String[] {"SRV"}); String[] astring = attributes.get("srv").get().toString().split(" ", 4); return new String[] {astring[3], astring[2]}; } catch (Throwable var6) { return new String[] {serverHost, Integer.toString(25565)}; } }
Example #14
Source File: DNS.java From RDFS with Apache License 2.0 | 6 votes |
/** * Returns the hostname associated with the specified IP address by the * provided nameserver. * * @param hostIp * The address to reverse lookup * @param ns * The host name of a reachable DNS server * @return The host name associated with the provided IP * @throws NamingException * If a NamingException is encountered */ public static String reverseDns(InetAddress hostIp, String ns) throws NamingException { // // Builds the reverse IP lookup form // This is formed by reversing the IP numbers and appending in-addr.arpa // String[] parts = hostIp.getHostAddress().split("\\."); String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa"; DirContext ictx = new InitialDirContext(); Attributes attribute = ictx.getAttributes("dns://" // Use "dns:///" if the default + ((ns == null) ? "" : ns) + // nameserver is to be used "/" + reverseIP, new String[] { "PTR" }); ictx.close(); return attribute.get("PTR").get().toString(); }
Example #15
Source File: JndiLdap.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 6 votes |
private static String dnFromUser(String username) throws NamingException { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, "ldap://ldap.example.com"); props.put(Context.REFERRAL, "ignore"); InitialDirContext context = new InitialDirContext(props); SearchControls ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[]{"givenName", "sn"}); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> answers = context.search("dc=People,dc=example,dc=com", "(uid=" + username + ")", ctrls); SearchResult result = answers.next(); return result.getNameInNamespace(); }
Example #16
Source File: JndiLdap.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 6 votes |
static boolean authenticate(String username, String password) { try { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, "ldap://ldap.example.com"); props.put(Context.REFERRAL, "ignore"); props.put(Context.SECURITY_PRINCIPAL, dnFromUser(username)); props.put(Context.SECURITY_CREDENTIALS, password); new InitialDirContext(props); return true; } catch (NamingException e) { return false; } }
Example #17
Source File: AbstractITCase.java From syncope with Apache License 2.0 | 6 votes |
@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" }) protected InitialDirContext getLdapResourceDirContext(final String bindDn, final String bindPwd) throws NamingException { ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP); ConnInstanceTO ldapConn = connectorService.read(ldapRes.getConnector(), Locale.ENGLISH.getLanguage()); Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + ldapConn.getConf("host").get().getValues().get(0) + ':' + ldapConn.getConf("port").get().getValues().get(0) + '/'); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDn == null ? ldapConn.getConf("principal").get().getValues().get(0) : bindDn); env.put(Context.SECURITY_CREDENTIALS, bindPwd == null ? ldapConn.getConf("credentials").get().getValues().get(0) : bindPwd); return new InitialDirContext(env); }
Example #18
Source File: LdapConnectionManagerService.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
private DirContext getConnection(final Hashtable<String, String> properties, final SSLContext sslContext) throws NamingException { ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(LdapConnectionManagerService.class); try { if (sslContext != null) { ThreadLocalSSLSocketFactory.setSSLSocketFactory(sslContext.getSocketFactory()); properties.put("java.naming.ldap.factory.socket", ThreadLocalSSLSocketFactory.class.getName()); } if (SECURITY_LOGGER.isTraceEnabled()) { Hashtable<String, String> logProperties; if (properties.containsKey(Context.SECURITY_CREDENTIALS)) { logProperties = new Hashtable<String, String>(properties); logProperties.put(Context.SECURITY_CREDENTIALS, "***"); } else { logProperties = properties; } SECURITY_LOGGER.tracef("Connecting to LDAP with properties (%s)", logProperties.toString()); } return new InitialDirContext(properties); } finally { if (sslContext != null) { ThreadLocalSSLSocketFactory.removeSSLSocketFactory(); } WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old); } }
Example #19
Source File: NamingManager.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public static Context getURLContext( String scheme, Hashtable<?,?> environment) throws NamingException { return new InitialDirContext() { public Attributes getAttributes(String name, String[] attrIds) throws NamingException { return new BasicAttributes() { public Attribute get(String attrID) { BasicAttribute ba = new BasicAttribute(attrID); ba.add("1 1 99 b.com."); ba.add("0 0 88 a.com."); // 2nd has higher priority return ba; } }; } }; }
Example #20
Source File: LegacyLDAPSecuritySettingPluginTest.java From activemq-artemis with Apache License 2.0 | 6 votes |
@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()); } 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")); }
Example #21
Source File: LdapConfigValidator.java From cloudbreak with Apache License 2.0 | 6 votes |
private void validateLdapConnection(String protocol, String serverHost, Integer serverPort, String bindDn, String bindPassword) { try { LOGGER.debug("Validate connection to LDAP host: '{}', port: '{}', protocol: '{}'.", serverHost, serverPort, protocol); //BEGIN GENERATED CODE Hashtable<String, String> env = new Hashtable<>(); //END GENERATED CODE env.put("com.sun.jndi.ldap.read.timeout", "1000"); env.put("com.sun.jndi.ldap.connect.timeout", "5000"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); String url = new StringBuilder(protocol). append("://"). append(serverHost). append(':'). append(serverPort).toString(); env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDn); env.put(Context.SECURITY_CREDENTIALS, bindPassword); Context ctx = new InitialDirContext(env); ctx.close(); } catch (NamingException e) { throw new BadRequestException("Failed to connect to LDAP server: " + e.getMessage(), e); } }
Example #22
Source File: LDAPQueryBuilder.java From flowable-engine with Apache License 2.0 | 5 votes |
public String buildQueryGroupsForUser(final LDAPConfiguration ldapConfigurator, final String userId) { String searchExpression = null; if (ldapConfigurator.getQueryGroupsForUser() != null) { // Fetch the dn of the user LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator); String userDn = ldapTemplate.execute(new LDAPCallBack<String>() { @Override public String executeInContext(InitialDirContext initialDirContext) { String userDnSearch = buildQueryByUserId(ldapConfigurator, userId); try { String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn(); NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, userDnSearch, createSearchControls(ldapConfigurator)); while (namingEnum.hasMore()) { // Should be only one SearchResult result = (SearchResult) namingEnum.next(); return result.getNameInNamespace(); } namingEnum.close(); } catch (NamingException e) { LOGGER.debug("Could not find user dn : {}", e.getMessage(), e); } return null; } }); searchExpression = MessageFormat.format(ldapConfigurator.getQueryGroupsForUser(), Rdn.escapeValue(userDn)); } else { searchExpression = userId; } return searchExpression; }
Example #23
Source File: LDAPUserQueryImpl.java From flowable-engine with Apache License 2.0 | 5 votes |
protected UserEntity findById(final String userId) { LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator); return ldapTemplate.execute(new LDAPCallBack<UserEntity>() { @Override public UserEntity executeInContext(InitialDirContext initialDirContext) { try { String searchExpression = ldapConfigurator.getLdapQueryBuilder().buildQueryByUserId(ldapConfigurator, userId); String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn(); NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls()); UserEntity user = new UserEntityImpl(); while (namingEnum.hasMore()) { // Should be only one SearchResult result = (SearchResult) namingEnum.next(); mapSearchResultToUser(result, user); } namingEnum.close(); return user; } catch (NamingException ne) { LOGGER.error("Could not find user {} : {}", userId, ne.getMessage(), ne); return null; } } }); }
Example #24
Source File: LDAPConnectionUtil.java From flowable-engine with Apache License 2.0 | 5 votes |
public static void closeDirectoryContext(InitialDirContext initialDirContext) { try { initialDirContext.close(); } catch (NamingException e) { LOGGER.warn("Could not close InitialDirContext correctly!", e); } }
Example #25
Source File: LdapUserAuthenticator.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public Principal authenticate(Properties props, DistributedMember member) { String userName = props.getProperty(UserPasswordAuthInit.USER_NAME); if (userName == null) { throw new AuthenticationFailedException( "LdapUserAuthenticator: user name property [" + UserPasswordAuthInit.USER_NAME + "] not provided"); } String passwd = props.getProperty(UserPasswordAuthInit.PASSWORD); if (passwd == null) { passwd = ""; } Properties env = new Properties(); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, this.ldapUrlScheme + this.ldapServer + '/' + this.basedn); String fullentry = "uid=" + userName + "," + this.basedn; env.put(Context.SECURITY_PRINCIPAL, fullentry); env.put(Context.SECURITY_CREDENTIALS, passwd); try { DirContext ctx = new InitialDirContext(env); ctx.close(); } catch (Exception e) { //TODO:hitesh need to add getCause message throw new AuthenticationFailedException( "LdapUserAuthenticator: Failure with provided username, password " + "combination for user name: " + userName); } return new UsernamePrincipal(userName); }
Example #26
Source File: LDAPUserQueryImpl.java From flowable-engine with Apache License 2.0 | 5 votes |
protected List<User> executeUsersQuery(final String searchExpression) { LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator); return ldapTemplate.execute(new LDAPCallBack<List<User>>() { @Override public List<User> executeInContext(InitialDirContext initialDirContext) { List<User> result = new ArrayList<>(); try { String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn(); NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls()); while (namingEnum.hasMore()) { SearchResult searchResult = (SearchResult) namingEnum.next(); UserEntity user = new UserEntityImpl(); mapSearchResultToUser(searchResult, user); result.add(user); } namingEnum.close(); } catch (NamingException ne) { LOGGER.debug("Could not execute LDAP query: {}", ne.getMessage(), ne); return null; } return result; } }); }
Example #27
Source File: MailBoxValidator.java From spring-boot with Apache License 2.0 | 5 votes |
private ArrayList getMX(String hostName) throws NamingException { // Perform a DNS lookup for MX records in the domain Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx = new InitialDirContext(env); Attributes attrs = ictx.getAttributes(hostName, new String[]{"MX"}); Attribute attr = attrs.get("MX"); // if we don't have an MX record, try the machine itself if ((attr == null) || (attr.size() == 0)) { attrs = ictx.getAttributes(hostName, new String[]{"A"}); attr = attrs.get("A"); if (attr == null) throw new NamingException("No match for name '" + hostName + "'"); } // Huzzah! we have machines to try. Return them as an array list // NOTE: We SHOULD take the preference into account to be absolutely // correct. This is left as an exercise for anyone who cares. ArrayList res = new ArrayList(); NamingEnumeration en = attr.getAll(); while (en.hasMore()) { String mailhost; String x = (String) en.next(); String f[] = x.split(" "); // THE fix ************* if (f.length == 1) mailhost = f[0]; else if (f[1].endsWith(".")) mailhost = f[1].substring(0, (f[1].length() - 1)); else mailhost = f[1]; // THE fix ************* res.add(mailhost); } return res; }
Example #28
Source File: TestJNDIRealm.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
private DirContext mockDirContext(NamingEnumeration<SearchResult> namingEnumeration) throws NamingException { DirContext dirContext = EasyMock.createNiceMock(InitialDirContext.class); EasyMock.expect(dirContext.search(EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyObject(SearchControls.class))) .andReturn(namingEnumeration) .times(2); EasyMock.expect(dirContext.getNameParser("")) .andReturn(new NameParserImpl()).times(2); EasyMock.expect(dirContext.getNameInNamespace()) .andReturn("ANY NAME") .times(2); EasyMock.replay(dirContext); return dirContext; }
Example #29
Source File: DNSUtilsImpl.java From BiglyBT with GNU General Public License v2.0 | 5 votes |
@Override public DNSDirContextImpl getDirContextForServer( String dns_server_ip ) throws NamingException { Hashtable env = new Hashtable(); env.put( Context.INITIAL_CONTEXT_FACTORY, getFactory()); env.put( Context.PROVIDER_URL, "dns://"+dns_server_ip+"/" ); return( new DNSDirContextImpl( new InitialDirContext( env ))); }
Example #30
Source File: SRV2URIs.java From etcd4j with Apache License 2.0 | 5 votes |
/** * Convert given DNS SRV address to array of URIs * * @param srvName complete DNS name to resolve to URIs * @return Array of URIs * @throws NamingException if DNS name was invalid */ public static URI[] fromDNSName(String srvName) throws NamingException { List<URI> uris = new ArrayList<>(); Hashtable<String, String> env = new Hashtable<>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); env.put("java.naming.provider.url", "dns:"); DirContext ctx = new InitialDirContext(env); Attributes attributes = ctx.getAttributes(srvName, new String[]{"SRV"}); NamingEnumeration<? extends Attribute> records = attributes.getAll(); while (records.hasMore()) { Attribute next = records.next(); @SuppressWarnings("unchecked") NamingEnumeration<String> values = (NamingEnumeration<String>) next.getAll(); while (values.hasMore()) { String dns = values.next(); String[] split = dns.split(" "); String port = split[2]; String host = split[3]; if (host.endsWith(".")) { host = host.substring(0, host.length() - 1); } URI uri = URI.create("http://" + host + ":" + port); uris.add(uri); } } return uris.toArray(new URI[uris.size()]); }