List of usage examples for javax.naming Context REFERRAL
String REFERRAL
To view the source code for javax.naming Context REFERRAL.
Click Source Link
From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java
@Override public void configure(String id, Properties properties) throws PIPException { /*/* w w w . j av a 2 s .c om*/ * Handle the standard properties */ super.configure(id, properties); String propertyPrefix = id + "."; /* * Configure the LDAP environment: I think the only required property is the provider_url */ if (!this.configureStringProperty(propertyPrefix, Context.PROVIDER_URL, properties, null)) { throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No " + propertyPrefix + Context.PROVIDER_URL); } this.configureStringProperty(propertyPrefix, Context.AUTHORITATIVE, properties, null); this.configureIntegerProperty(propertyPrefix, Context.BATCHSIZE, properties, null); this.configureStringProperty(propertyPrefix, Context.DNS_URL, properties, null); this.configureStringProperty(propertyPrefix, Context.INITIAL_CONTEXT_FACTORY, properties, DEFAULT_CONTEXT_FACTORY); this.configureStringProperty(propertyPrefix, Context.LANGUAGE, properties, null); this.configureStringProperty(propertyPrefix, Context.OBJECT_FACTORIES, properties, null); this.configureStringProperty(propertyPrefix, Context.REFERRAL, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_AUTHENTICATION, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_CREDENTIALS, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_PRINCIPAL, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_PROTOCOL, properties, null); this.configureStringProperty(propertyPrefix, Context.STATE_FACTORIES, properties, null); this.configureStringProperty(propertyPrefix, Context.URL_PKG_PREFIXES, properties, null); String ldapScopeValue = properties.getProperty(propertyPrefix + PROP_LDAP_SCOPE, DEFAULT_SCOPE); if (LDAP_SCOPE_SUBTREE.equals(ldapScopeValue)) { this.ldapScope = SearchControls.SUBTREE_SCOPE; } else if (LDAP_SCOPE_OBJECT.equals(ldapScopeValue)) { this.ldapScope = SearchControls.OBJECT_SCOPE; } else if (LDAP_SCOPE_ONELEVEL.equals(ldapScopeValue)) { this.ldapScope = SearchControls.ONELEVEL_SCOPE; } else { this.logger.warn("Invalid LDAP Scope value '" + ldapScopeValue + "'; using " + DEFAULT_SCOPE); this.ldapScope = SearchControls.SUBTREE_SCOPE; } /* * Get list of resolvers defined for this LDAP Engine */ String resolversList = properties.getProperty(propertyPrefix + PROP_RESOLVERS); if (resolversList == null || resolversList.isEmpty()) { throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No " + propertyPrefix + PROP_RESOLVERS); } /* * Iterate the resolvers */ for (String resolver : Splitter.on(',').trimResults().omitEmptyStrings().split(resolversList)) { /* * Get the LDAPResolver for this LDAPEngine */ String resolverClassName = properties .getProperty(propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname"); if (resolverClassName == null) { throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No " + propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname"); } LDAPResolver ldapResolverNew = null; try { Class<?> classResolver = Class.forName(resolverClassName); if (!LDAPResolver.class.isAssignableFrom(classResolver)) { this.logger.error("LDAPResolver class " + resolverClassName + " does not implement " + LDAPResolver.class.getCanonicalName()); throw new PIPException("LDAPResolver class " + resolverClassName + " does not implement " + LDAPResolver.class.getCanonicalName()); } ldapResolverNew = LDAPResolver.class.cast(classResolver.newInstance()); } catch (Exception ex) { this.logger.error("Exception instantiating LDAPResolver for class '" + resolverClassName + "': " + ex.getMessage(), ex); throw new PIPException("Exception instantiating LDAPResolver for class '" + resolverClassName + "'", ex); } assert ldapResolverNew != null; ldapResolverNew.configure(propertyPrefix + PROP_RESOLVER + "." + resolver, properties, this.getIssuer()); this.ldapResolvers.add(ldapResolverNew); } }
From source file:org.apache.ranger.ldapconfigcheck.LdapConfigCheckMain.java
public static void main(String[] args) { CommandLineOptions cli = new CommandLineOptions(args); cli.parse();/*from ww w . ja v a 2 s.co 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 w w w .j a va 2 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); }
From source file:org.apache.zeppelin.realm.LdapRealm.java
protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx, final LdapContextFactory ldapContextFactory, Session session) throws NamingException { final Set<String> roleNames = new HashSet<>(); final Set<String> groupNames = new HashSet<>(); final String userName; if (getUserLowerCase()) { log.debug("userLowerCase true"); userName = userNameIn.toLowerCase(); } else {//from w w w . j a v a2 s .c o m userName = userNameIn; } String userDn = getUserDnForSearch(userName); // Activate paged results int pageSize = getPagingSize(); if (log.isDebugEnabled()) { log.debug("Ldap PagingSize: " + pageSize); } int numResults = 0; byte[] cookie = null; try { ldapCtx.addToEnvironment(Context.REFERRAL, "ignore"); ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); do { // ldapsearch -h localhost -p 33389 -D // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)' NamingEnumeration<SearchResult> searchResultEnum = null; SearchControls searchControls = getGroupSearchControls(); try { if (groupSearchEnableMatchingRuleInChain) { searchResultEnum = ldapCtx.search(getGroupSearchBase(), String .format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn), searchControls); while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope numResults++; final SearchResult group = searchResultEnum.next(); Attribute attribute = group.getAttributes().get(getGroupIdAttribute()); String groupName = attribute.get().toString(); String roleName = roleNameFor(groupName); if (roleName != null) { roleNames.add(roleName); } else { roleNames.add(groupName); } } } else { // Default group search filter String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass); // If group search filter is defined in Shiro config, then use it if (groupSearchFilter != null) { searchFilter = expandTemplate(groupSearchFilter, userName); //searchFilter = String.format("%1$s", groupSearchFilter); } if (log.isDebugEnabled()) { log.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + getGroupSearchBase() + "|" + searchFilter + "|" + groupSearchScope); } searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls); while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope numResults++; final SearchResult group = searchResultEnum.next(); addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory); } } } catch (PartialResultException e) { log.debug("Ignoring PartitalResultException"); } finally { if (searchResultEnum != null) { searchResultEnum.close(); } } // Re-activate paged results ldapCtx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException e) { log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException."); } catch (IOException e) { log.error("Unabled to setup paged results"); } // save role names and group names in session so that they can be // easily looked up outside of this object session.setAttribute(SUBJECT_USER_ROLES, roleNames); session.setAttribute(SUBJECT_USER_GROUPS, groupNames); if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) { ((MutablePrincipalCollection) principals).addAll(groupNames, getName()); } if (log.isDebugEnabled()) { log.debug("User RoleNames: " + userName + "::" + roleNames); } return roleNames; }
From source file:org.artifactory.security.ldap.ArtifactoryLdapAuthenticator.java
static LdapContextSource createSecurityContext(LdapSetting ldapSetting) { String url = ldapSetting.getLdapUrl(); String scheme = getLdapScheme(url); String baseUrl = getLdapBaseUrl(scheme, url); DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(scheme + baseUrl); contextSource.setBase(adjustBase(url.substring((scheme + baseUrl).length()))); // set default connection timeout, read timeout and referral strategy. Map<String, Object> env = new HashMap<>(); String connectTimeout = ArtifactoryHome.get().getArtifactoryProperties() .getProperty("artifactory.security.ldap.connect.timeoutMillis", "10000"); env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout); String readTimeout = ArtifactoryHome.get().getArtifactoryProperties() .getProperty("artifactory.security.ldap.socket.timeoutMillis", "15000"); env.put("com.sun.jndi.ldap.read.timeout", readTimeout); String referralStrategy = ArtifactoryHome.get().getArtifactoryProperties() .getProperty("artifactory.security.ldap.referralStrategy", "follow"); env.put(Context.REFERRAL, referralStrategy); String poolIdleTimeout = ArtifactoryHome.get().getArtifactoryProperties() .getProperty("artifactory.security.ldap.pool.timeoutMillis", null); if (poolIdleTimeout != null) { env.put("com.sun.jndi.ldap.connect.pool.timeout", poolIdleTimeout); }/*ww w. j a v a 2 s . c o m*/ contextSource.setBaseEnvironmentProperties(env); SearchPattern searchPattern = ldapSetting.getSearch(); if (searchPattern != null) { if (PathUtils.hasText(searchPattern.getManagerDn())) { contextSource.setUserDn(searchPattern.getManagerDn()); contextSource.setPassword(CryptoHelper.decryptIfNeeded(searchPattern.getManagerPassword())); } else { contextSource.setAnonymousReadOnly(true); } } try { contextSource.afterPropertiesSet(); } catch (Exception e) { throw new RuntimeException(e); } return contextSource; }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided * username and credential./*from w w w . j av a 2 s . c o m*/ * * @return the Initial Ldap Context to be used to perform searches, etc. * @throws NamingException LDAP binding error. */ protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential) throws NamingException { Properties env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory()); env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication()); env.setProperty(Context.PROVIDER_URL, getProviderUrl()); env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol())); // Set defaults for key values if they are missing String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (factoryName == null) { factoryName = "com.sun.jndi.ldap.LdapCtxFactory"; env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName); } String authType = env.getProperty(Context.SECURITY_AUTHENTICATION); if (authType == null) env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); String protocol = env.getProperty(Context.SECURITY_PROTOCOL); String providerURL = getProviderUrl(); // Use localhost if providerUrl not set if (providerURL == null) { providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389"); } else { // In case user configured provided URL if (providerURL.startsWith("ldaps")) { protocol = "ssl"; env.setProperty(Context.SECURITY_PROTOCOL, "ssl"); } } env.setProperty(Context.PROVIDER_URL, providerURL); if (securityPrincipal != null && !"".equals(securityPrincipal)) env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal); if (securityCredential != null && !"".equals(securityCredential)) env.put(Context.SECURITY_CREDENTIALS, securityCredential); // always follow referrals transparently env.put(Context.REFERRAL, "follow"); // Logon into LDAP server if (logger.isDebugEnabled()) logger.debug("Logging into LDAP server, env=" + env); InitialLdapContext ctx = new InitialLdapContext(env, null); if (logger.isDebugEnabled()) logger.debug("Logged into LDAP server, " + ctx); return ctx; }
From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java
private LdapContext getLdapContext() throws NamingException, AuthenticationException { if (config == null) { throw new NamingException("LDAP not configured"); }/*from www .ja v a2s .c om*/ if (StringUtils.isBlank(config.getProviderUrl())) { throw new NamingException("No LDAP server available"); } if (StringUtils.isBlank(config.getUsername()) || StringUtils.isBlank(config.getPassword())) { throw new AuthenticationException("No LDAP credentials available"); } String ctxFactory = config.getCtxFactory(); if (StringUtils.isBlank(ctxFactory)) { ctxFactory = DEFAULT_CONTEXT_FACTORY; } String authentication = config.getAuthentication(); if (StringUtils.isBlank(authentication)) { authentication = SIMPLE_AUTHENTICATION; } Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFactory); env.put(Context.PROVIDER_URL, config.getProviderUrl()); env.put(Context.SECURITY_PRINCIPAL, config.getUsername()); env.put(Context.SECURITY_CREDENTIALS, config.getPassword()); env.put(Context.SECURITY_AUTHENTICATION, authentication); if (StringUtils.isNotBlank(config.getReferral())) { env.put(Context.REFERRAL, config.getReferral()); } if (config.getProviderUrl().startsWith(LDAPS_SCHEME)) { env.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$ if (config.isSslNoVerify()) { env.put(JNDI_SOCKET_FACTORY, LDAPTrustAllSocketFactory.class.getName()); } } // Gemini-specific properties env.put(JNDIConstants.BUNDLE_CONTEXT, FrameworkUtil.getBundle(LDAPClient.class).getBundleContext()); // com.sun.jndi.ldap.LdapCtxFactory specific properties env.put(READ_TIMEOUT, DEFAULT_READ_TIMEOUT); env.put(USE_CONNECTION_POOLING, "true"); //$NON-NLS-1$ // extremly ugly classloading workaround: // com.sun.jndi.ldap.LdapCtxFactory uses Class.forName() to load the socket factory, shame on them! InitialLdapContext ctx = null; ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(LDAPTrustAllSocketFactory.class.getClassLoader()); ctx = new InitialLdapContext(env, null); } finally { if (classloader != null) { Thread.currentThread().setContextClassLoader(classloader); } } return ctx; }
From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java
public void collect() { // Setup initial LDAP properties Properties env = new Properties(); Properties props = getProperties(); // Set our default factory name if one is not given String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (factoryName == null) { env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); }// w w w .j a va 2 s.co m // Set the LDAP url if (isSSL()) { env.put("java.naming.ldap.factory.socket", LDAPSSLSocketFactory.class.getName()); env.put(Context.SECURITY_PROTOCOL, "ssl"); } String providerUrl = "ldap://" + getHostname() + ":" + getPort(); env.setProperty(Context.PROVIDER_URL, providerUrl); // For log track setSource(providerUrl); // Follow referrals automatically env.setProperty(Context.REFERRAL, "follow"); // Base DN String baseDN = props.getProperty(PROP_BASEDN); if (baseDN == null) { setErrorMessage("No Base DN given, refusing login"); setAvailability(false); return; } // Search filter String filter = props.getProperty(PROP_FILTER); // Load any information we may need to bind String bindDN = props.getProperty(PROP_BINDDN); String bindPW = props.getProperty(PROP_BINDPW); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } if (log.isDebugEnabled()) { log.debug("Using LDAP environment: " + env); } try { startTime(); InitialLdapContext ctx = new InitialLdapContext(env, null); endTime(); setAvailability(true); // If a search filter is specified, run the search and return the // number of matches as a metric if (filter != null) { log.debug("Using LDAP filter=" + filter); NamingEnumeration answer = ctx.search(baseDN, filter, getSearchControls()); long matches = 0; while (answer.hasMore()) { matches++; answer.next(); } setValue("NumberofMatches", matches); } } catch (Exception e) { setAvailability(false); if (log.isDebugEnabled()) { log.debug("LDAP check failed: " + e, e); } setErrorMessage("LDAP check failed: " + e); } }
From source file:org.jkcsoft.java.util.JndiHelper.java
public static DirContext getDirContext(BehavioralContext bctx, Object principal, Object credentials) throws NamingException { DirContext ctx = null;//from w w w . jav a 2 s . co m Configuration tconfig = bctx.getConfig(); String ldapProvider = "ldap" + "://" + tconfig.getString(Constants.KEY_AD_HOST) + ":" + tconfig.getString(Constants.KEY_AD_PORT) + "/" + tconfig.getString(Constants.KEY_AD_ROOT_DN); log.info("Using LDAP url: [" + ldapProvider + "]"); // String url, String contextFactoryName, Hashtable jndiEnv = new Hashtable(); jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); jndiEnv.put(Context.PROVIDER_URL, ldapProvider); jndiEnv.put(Context.REFERRAL, "follow"); if (tconfig.getBoolean(Constants.KEY_AD_SSL)) { log.info("Using SSL for LDAP"); jndiEnv.put(Context.SECURITY_PROTOCOL, "ssl"); } jndiEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); if (principal != null) jndiEnv.put(Context.SECURITY_PRINCIPAL, principal); if (credentials != null) jndiEnv.put(Context.SECURITY_CREDENTIALS, credentials); try { // Creating the JNDI directory context (with LDAP context // factory), performs an LDAP bind to the LDAP provider thereby // authenticating the username/pw. ctx = new InitialDirContext(jndiEnv); } catch (NamingException ex) { log.error("Directory context init failed", ex); throw ex; } return ctx; }
From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java
/** * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided * username and credential.//from w w w .jav a2 s .c o m * * @return the Initial Ldap Context to be used to perform searches, etc. * @throws NamingException LDAP binding error. */ protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential) throws NamingException { Properties env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory()); env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication()); env.setProperty(Context.PROVIDER_URL, getProviderUrl()); env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol())); // Set defaults for key values if they are missing String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (factoryName == null) { factoryName = "com.sun.jndi.ldap.LdapCtxFactory"; env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName); } String authType = env.getProperty(Context.SECURITY_AUTHENTICATION); if (authType == null) env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); String protocol = env.getProperty(Context.SECURITY_PROTOCOL); String providerURL = getProviderUrl(); // Use localhost if providerUrl not set if (providerURL == null) { //providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389"); if (protocol != null && protocol.equals("ssl")) { // We should use Start TLS extension? providerURL = "ldaps://localhost:636"; } else { providerURL = "ldap://localhost:389"; } } env.setProperty(Context.PROVIDER_URL, providerURL); env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal); env.put(Context.SECURITY_CREDENTIALS, securityCredential); // always follow referrals transparently env.put(Context.REFERRAL, "follow"); // Logon into LDAP server if (logger.isDebugEnabled()) logger.debug("Logging into LDAP server, env=" + env); InitialLdapContext ctx = new InitialLdapContext(env, null); if (logger.isDebugEnabled()) logger.debug("Logged into LDAP server, " + ctx); return ctx; }