List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY
String INITIAL_CONTEXT_FACTORY
To view the source code for javax.naming Context INITIAL_CONTEXT_FACTORY.
Click Source Link
From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java
/** * Load a default set of properties to use when connecting to the LDAP server. If basic authentication is needed, * the caller must set Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS and Context.SECURITY_AUTHENTICATION * appropriately.//from w w w .ja v a 2 s. c om * * @return properties that are to be used when connecting to LDAP server */ private Properties getProperties() { Properties env = new Properties(); // Map all user options into into our environment Iterator iter = options.entrySet().iterator(); while (iter.hasNext()) { Entry entry = (Entry) iter.next(); if ((entry.getKey() != null) && (entry.getValue() != null)) { env.put(entry.getKey(), entry.getValue()); } } // 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"); } // Setup SSL if requested String protocol = env.getProperty(Context.SECURITY_PROTOCOL); if ("ssl".equals(protocol)) { String ldapSocketFactory = env.getProperty("java.naming.ldap.factory.socket"); if (ldapSocketFactory == null) { env.put("java.naming.ldap.factory.socket", UntrustedSSLSocketFactory.class.getName()); } env.put(Context.SECURITY_PROTOCOL, "ssl"); } // Set the LDAP url String providerUrl = env.getProperty(Context.PROVIDER_URL); if (providerUrl == null) { providerUrl = "ldap://localhost:" + (((protocol != null) && protocol.equals("ssl")) ? "636" : "389"); } env.setProperty(Context.PROVIDER_URL, providerUrl); // Follow referrals automatically env.setProperty(Context.REFERRAL, "ignore");//BZ:582471- active directory query change return env; }
From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java
public void testRunAsMethod() throws Exception { log.debug("+++ testRunAsMethod()"); Properties env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory"); env.setProperty(Context.SECURITY_PRINCIPAL, "jduke"); env.setProperty(Context.SECURITY_CREDENTIALS, "theduke"); InitialContext ctx = new InitialContext(env); Object obj = ctx.lookup("jacc/Secured"); obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class); SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj; log.debug("Found SecuredServiceRemoteHome"); SecuredServiceRemote bean = home.create(); log.debug("Created SecuredServiceRemote"); Principal callerIdentity = new SimplePrincipal("jduke"); Principal runAsIdentity = new SimplePrincipal("runAsUser"); HashSet expectedCallerRoles = new HashSet(); expectedCallerRoles.add("groupMemberCaller"); expectedCallerRoles.add("userCaller"); expectedCallerRoles.add("allAuthCaller"); expectedCallerRoles.add("webUser"); HashSet expectedRunAsRoles = new HashSet(); expectedRunAsRoles.add("identitySubstitutionCaller"); expectedRunAsRoles.add("extraRunAsRole"); CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles); bean.runAsMethod(info);/*ww w . j av a 2 s. c om*/ bean.remove(); }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test to make sure that if anonymous binds are allowed a user may search * within a a partition./*from ww w . ja v a 2s . com*/ * * @throws Exception if anything goes wrong */ @Test public void testAnonymousBindsEnabledBaseSearch() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialDirContext ctx = new InitialDirContext(env); SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); NamingEnumeration<SearchResult> list = ctx.search("dc=apache,dc=org", "(objectClass=*)", cons); SearchResult result = null; if (list.hasMore()) { result = list.next(); } assertFalse(list.hasMore()); list.close(); assertNotNull(result); assertNotNull(result.getAttributes().get("dc")); }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * Setup environment./*from w w w . j av a 2 s . c om*/ * @param props * @throws SourceUnavailableException */ protected void setupEnvironment(Properties props) throws SourceUnavailableException { this.environment.put("com.sun.jndi.ldap.connect.pool", "true"); this.environment.put(Context.INITIAL_CONTEXT_FACTORY, props.getProperty("INITIAL_CONTEXT_FACTORY")); this.environment.put(Context.PROVIDER_URL, props.getProperty("PROVIDER_URL")); this.environment.put(Context.SECURITY_AUTHENTICATION, props.getProperty("SECURITY_AUTHENTICATION")); this.environment.put(Context.SECURITY_PRINCIPAL, props.getProperty("SECURITY_PRINCIPAL")); String password = props.getProperty("SECURITY_CREDENTIALS"); password = Morph.decryptIfFile(password); this.environment.put(Context.SECURITY_CREDENTIALS, password); if (props.getProperty("SECURITY_PROTOCOL") != null) { this.environment.put(Context.SECURITY_PROTOCOL, "ssl"); } Context context = null; try { log.debug("Creating Directory Context"); context = new InitialDirContext(this.environment); } catch (AuthenticationException ex) { log.error("Error with Authentication " + ex.getMessage(), ex); throw new SourceUnavailableException("Error with Authentication ", ex); } catch (NamingException ex) { log.error("Naming Error " + ex.getMessage(), ex); throw new SourceUnavailableException("Naming Error", ex); } finally { if (context != null) { try { context.close(); } catch (NamingException ne) { // squelch, since it is already closed } } } log.info("Success in connecting to LDAP"); this.nameAttributeName = props.getProperty("Name_AttributeType"); if (this.nameAttributeName == null) { log.error("Name_AttributeType not defined"); } this.subjectIDAttributeName = props.getProperty("SubjectID_AttributeType"); if (this.subjectIDAttributeName == null) { log.error("SubjectID_AttributeType not defined"); } this.descriptionAttributeName = props.getProperty("Description_AttributeType"); if (this.descriptionAttributeName == null) { log.error("Description_AttributeType not defined"); } }
From source file:org.springframework.ldap.odm.tools.SchemaToJava.java
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); }/* w ww . j a va 2 s.co m*/ 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; }
From source file:org.mule.providers.ldap.util.DSManager.java
/** * Sets the system context root to null. * /*ww w. j a v a 2 s . com*/ * @see junit.framework.TestCase#tearDown() */ public synchronized void stop() throws Exception { logger.debug("DS is stopping ..."); if (!running) { logger.debug("stop() called while is not running"); if (checkSocketNotConnected()) { return; } else { logger.debug("stop() forced"); } } // super.tearDown(); Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, "ou=system"); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.directory.server.jndi.ServerContextFactory"); env.putAll(new ShutdownConfiguration().toJndiEnvironment()); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); try { new InitialContext(env); } catch (Exception e) { // ignored // dont remove try catch block!! } sysRoot = null; doDelete(configuration.getWorkingDirectory()); configuration = new MutableServerStartupConfiguration(); logger.debug("DS waiting for socket release ..."); // wait for shutdown int i = 0; while (i < 20 && !checkSocketNotConnected()) { Thread.sleep(2000); i++; logger.debug("Try " + i); } if (!checkSocketNotConnected()) { throw new Exception("Shutdown of DS not successfull, server socket was not freed"); } logger.debug("DS now stopped!"); running = false; }
From source file:org.betaconceptframework.astroboa.engine.service.security.AstroboaLogin.java
private void initializeExternalIdentityStore(String identityStoreLocation) throws FailedLoginException { try {/*from w ww . ja v a 2 s . c om*/ InitialContext context = new InitialContext(); //First check to see if initial context has been initiated at all Hashtable<?, ?> env = context.getEnvironment(); String initialContextFactoryName = env != null ? (String) env.get(Context.INITIAL_CONTEXT_FACTORY) : null; if (StringUtils.isNotBlank(initialContextFactoryName)) { Object serviceReference = context.lookup(identityStoreLocation); if (!(serviceReference instanceof IdentityStore)) { if (!identityStoreLocation.endsWith("/local")) { //JNDIName is provided by the user and the object it references is not an instance of IdentityStore. //It is probably an instance of NamingContext which is on top of a local or remote service //Since JNDIName does not end with "/local" , try to locate the local service under the returned NamingContext identityStore = (IdentityStore) context.lookup(identityStoreLocation + "/local"); } else { throw new Exception("JNDI Name " + identityStoreLocation + " refers to an object whose type is not IdentityStore. Unable to locate. External Identity Store "); } } else { identityStore = (IdentityStore) serviceReference; } //TODO: It may also be the case another login to the identity store must be done } else { throw new Exception( "Initial Context Factory Name is blank therefore no initial context is configured, thus any lookup will result in exception." + "External Identity Store " + identityStoreLocation); } } catch (Exception e) { logger.error("", e); throw new FailedLoginException("During connection to external Identity Store " + identityStoreLocation); } }
From source file:org.openiam.idm.srvc.auth.spi.AbstractLoginModule.java
public LdapContext connect(String userName, String password, ManagedSysDto managedSys) throws NamingException { if (keystore != null && !keystore.isEmpty()) { System.setProperty("javax.net.ssl.trustStore", keystore); System.setProperty("javax.net.ssl.keyStorePassword", keystorePasswd); }//from w w w. jav a2 s.c o m if (managedSys == null) { log.debug("ManagedSys is null"); return null; } String hostUrl = managedSys.getHostUrl(); if (managedSys.getPort() > 0) { hostUrl = hostUrl + ":" + String.valueOf(managedSys.getPort()); } log.debug("connect: Connecting to target system: " + managedSys.getId()); log.debug("connect: Managed System object : " + managedSys); log.info(" directory login = " + managedSys.getUserId()); log.info(" directory login passwrd= *****"); log.info(" javax.net.ssl.trustStore= " + System.getProperty("javax.net.ssl.trustStore")); log.info(" javax.net.ssl.keyStorePassword= " + System.getProperty("javax.net.ssl.keyStorePassword")); Hashtable<String, String> envDC = new Hashtable(); envDC.put(Context.PROVIDER_URL, hostUrl); envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple envDC.put(Context.SECURITY_PRINCIPAL, userName); envDC.put(Context.SECURITY_CREDENTIALS, password); // Connections Pool configuration envDC.put("com.sun.jndi.ldap.connect.pool", "true"); // Here is an example of a command line that sets the maximum pool size to 20, the preferred pool size to 10, and the idle timeout to 5 minutes for pooled connections. envDC.put("com.sun.jndi.ldap.connect.pool.prefsize", "10"); envDC.put("com.sun.jndi.ldap.connect.pool.maxsize", "20"); envDC.put("com.sun.jndi.ldap.connect.pool.timeout", "300000"); LdapContext ldapContext = null; try { ldapContext = (LdapContext) new LdapCtxFactory().getInitialContext((Hashtable) envDC); } catch (CommunicationException ce) { log.error("Throw communication exception.", ce); } catch (NamingException ne) { log.error(ne.toString(), ne); } catch (Throwable e) { log.error(e.toString(), e); } return ldapContext; }
From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java
private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException { LdapContext ctx = null;/*from w ww . ja v a2s . 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:ldap.LdapApi.java
/** * open the directory connection.// w ww. j a v a2 s .c o m * @param url * @param dn * @param password * @param tracing * @return DirContext - context * @throws NamingException */ private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing) throws NamingException { /* * setup environment variables to sensible default valuse */ Hashtable env = new Hashtable(); // sanity check if (url == null) { throw new LdapException("URL not specified in openContext()!"); } // tracing on/off, 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, LdapConstants.ldapContext); // use default jndi provider 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 */ context = new InitialDirContext(env); if (context == null) { throw new NamingException( "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi."); } else { logger.info("context is not null"); } return context; }