List of usage examples for javax.naming Context SECURITY_PRINCIPAL
String SECURITY_PRINCIPAL
To view the source code for javax.naming Context SECURITY_PRINCIPAL.
Click Source Link
From source file:eu.uqasar.util.ldap.LdapManager.java
private LdapContext getConnection(LdapSettings settings, final String userName, final String password) throws CommunicationException, NamingException { Validate.notEmpty(settings.getAuthUserDN()); // bind by using the specified username/password Properties props = new Properties(); props.put(Context.SECURITY_PRINCIPAL, userName == null ? settings.getAuthUserDN() : userName); if (settings.getAuthUserPassword() != null || password != null) { props.put(Context.SECURITY_CREDENTIALS, password == null ? settings.getAuthUserPassword() : password); }//from w w w .ja v a 2s . co m // ensures that objectSID attribute values // will be returned as a byte[] instead of a String props.put("java.naming.ldap.attributes.binary", "objectSID"); // the following is helpful in debugging errors // props.put("com.sun.jndi.ldap.trace.ber", System.err); String ldapURL = String.format("ldap://%s:%s", settings.getHost(), settings.getPort()); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, ldapURL); props.put(Context.REFERRAL, "follow"); try { return new InitialLdapContext(props, null); } catch (CommunicationException e) { logger.warn(String.format("Failed to connect to %s:%s", settings.getHost(), settings.getPort()), e); throw e; } catch (NamingException e) { logger.warn(String.format("Failed to authenticate %s:%s", settings.getHost(), settings.getPort()), e); throw e; } }
From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java
/** * Gets and returns the entries from the server. * /*ww w . ja va 2 s. com*/ * @throws ToolCommandException * @throws NamingException */ public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException { // Connecting to the LDAP Server if (isDebugEnabled()) { notifyOutputListener("Connecting to LDAP server"); notifyOutputListener("Host: " + host); notifyOutputListener("Port: " + port); notifyOutputListener("User DN: " + user); notifyOutputListener("Base DN: " + baseDN); notifyOutputListener("Authentication: " + auth); } Hashtable env = new Hashtable(); env.put(Context.SECURITY_PRINCIPAL, user); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, auth); env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); DirContext ctx; try { ctx = new InitialDirContext(env); } catch (NamingException e) { throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage()); } // Setting up search scope SearchControls ctls = new SearchControls(); ctls.setSearchScope(scope); // Fetching entries try { return ctx.search(exportPoint, "(objectClass=*)", ctls); } catch (NamingException e) { throw new ToolCommandException("Could not retreive entries"); } }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * retrieve home directory of given user. * * @param inBenutzer/*from w w w . j a v a 2 s . com*/ * User object * @return path as string */ public String getUserHomeDirectory(User inBenutzer) { if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) { return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } Hashtable<String, String> env = getLdapConnectionSettings(); if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) { env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url")); 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(); // Authenticate via SASL EXTERNAL mechanism using client X.509 // certificate contained in JVM keystore ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); ctx.reconnect(null); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get("homeDirectory"); return (String) la.get(0); // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } catch (NamingException e) { logger.error("JNDI error:", e); return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin(); } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e); } } } } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); } else { env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); } DirContext ctx; String rueckgabe = ""; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer)); Attribute la = attrs.get("homeDirectory"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { logger.error(e); } return rueckgabe; }
From source file:org.openiam.spml2.spi.ldap.LdapConnectorImpl.java
public LdapContext connect(String userName, String password) { //LdapContext ctxLdap = null; Hashtable<String, String> envDC = new Hashtable(); //keystore = secres.getString("KEYSTORE"); System.setProperty("javax.net.ssl.trustStore", keystore); log.debug("Connecting to ldap using principal=" + userName); //envDC.put(Context.PROVIDER_URL,host); envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple envDC.put(Context.SECURITY_PRINCIPAL, userName); //"administrator@diamelle.local" envDC.put(Context.SECURITY_CREDENTIALS, password); // if (protocol != null && protocol.equalsIgnoreCase("SSL")) { // envDC.put(Context.SECURITY_PROTOCOL, protocol); // }//w w w .ja v a2 s . c o m try { return (new InitialLdapContext(envDC, null)); } catch (NamingException ne) { log.error(ne.getMessage()); } return null; }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind) throws AuthenticationException, NamingException { env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal); env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials); DirContext ctx = null;// ww w . j a v a 2 s . c o m try { ctx = new InitialDirContext(env); } catch (NamingException ne) { log.error("Failed to bind as: {}", ldapSecurityPrincipal); } // ensure we have the userPassword attribute at a minimum String[] attributeList = new String[] { "userPassword" }; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(attributeList); sc.setDerefLinkFlag(true); sc.setReturningObjFlag(false); sc.setTimeLimit(5000); String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")"; // Do the search NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc); if (!results.hasMore()) { log.warn("no valid user found."); return false; } SearchResult result = results.next(); log.debug("authenticating user: {}", result.getNameInNamespace()); if (bind) { // setup user context for binding Hashtable<String, String> userEnv = new Hashtable<String, String>(); userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); userEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); userEnv.put(Context.PROVIDER_URL, baseUrl); userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace()); userEnv.put(Context.SECURITY_CREDENTIALS, password); try { new InitialDirContext(userEnv); } catch (NamingException ne) { log.error("failed to authenticate user: " + result.getNameInNamespace()); throw ne; } } else { // get userPassword attribute Attribute up = result.getAttributes().get("userPassword"); if (up == null) { log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace()); return false; } byte[] userPasswordBytes = (byte[]) up.get(); String userPassword = new String(userPasswordBytes); // compare passwords - also handles encodings if (!passwordsMatch(password, userPassword)) { return false; } } return true; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets the initial context//from w w w. j a v a2s . c o m * * @param providerUrl * @param bindDN * @param bindPassword * @return */ public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) { List<String> trace = new ArrayList<String>(); LOGGER.debug("providerURL: " + providerUrl); trace.add("Attempting to connect to the LDAP server..."); if (providerUrl != null && providerUrl.startsWith("ldaps:")) { System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE); trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE); File ks = new File(PATH_TO_KEY_STORE); if (!ks.exists()) { trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE); } } if (providerUrl == null) { LOGGER.warn("LDAP provider URL should not be null."); return null; } Hashtable<String, Object> env = new Hashtable<String, Object>(); if (LOGGER.isDebugEnabled()) { env.put("com.sun.jndi.ldape.trace.ber", System.err); } env.put("java.naming.ldap.version", "3"); env.put("com.sun.jndi.ldap.connect.timeout", "10000"); env.put("com.sun.jndi.dns.timeout.initial", "2000"); env.put("com.sun.jndi.dns.timeout.retries", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); if ((bindDN != null) && !bindDN.equals("")) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDN); env.put(Context.SECURITY_CREDENTIALS, bindPassword); LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*")); trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****"); } else { LOGGER.debug("bind anonymous"); trace.add("Preparing to bind anonymously to the LDAP server"); } try { return new InitialLdapContext(env, null); } catch (NamingException e) { for (String msg : trace) { LOGGER.error(msg); } LOGGER.error("Getting the initial ldap context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); try { new InitialDirContext(env); } catch (NamingException e1) { LOGGER.error("Getting the initial dir context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; } }
From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java
/** * Configure {@link SSLContext} and create EJB client properties. * * @param clientName/*from w ww.j ava 2 s . co m*/ * @return * @throws Exception */ private Properties configureEjbClient(String clientName) throws Exception { // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init( KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()), KEYSTORE_PASSWORD.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray())); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); SSLContext.setDefault(sslContext); final Properties env = new Properties(); env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory"); env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST); env.put("jboss.naming.client.ejb.context", "true"); env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false"); env.put(Context.SECURITY_PRINCIPAL, "admin"); env.put(Context.SECURITY_CREDENTIALS, "testing"); // SSL related config parameters env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "true"); env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true"); return env; }
From source file:org.apache.directory.server.ldap.handlers.sasl.AbstractSaslCallbackHandler.java
/** * Convenience method for getting an environment suitable for acquiring * an {@link LdapContext} for the client. * //w ww .ja v a 2 s .com * @param session The current session. * @return An environment suitable for acquiring an {@link LdapContext} for the client. */ protected Hashtable<String, Object> getEnvironment(IoSession session) { Hashtable<String, Object> env = new Hashtable<>(); env.put(Context.PROVIDER_URL, session.getAttribute("baseDn")); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.directory.server.core.jndi.CoreContextFactory"); env.put(Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN); env.put(Context.SECURITY_CREDENTIALS, "secret"); env.put(Context.SECURITY_AUTHENTICATION, AuthenticationLevel.SIMPLE.toString()); return env; }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Returns <i>true</i> if the Active Directory account and password are * valid (e.g. a context can be successfully established) or <i>false</i> * otherwise./* w ww. ja va 2 s . c o m*/ * * @param anAccountName An Active Directory account name. * @param anAccountPassword An Active Directory account passowrd. * * @return <i>true</i> or <i>false</i> */ @SuppressWarnings("unchecked") public boolean isAccountValid(String anAccountName, String anAccountPassword) { boolean isValid = false; Logger appLogger = mAppMgr.getLogger(this, "isAccountValid"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); DataBag userBag = schemaUserBag(); userBag.setValueByName(LDAP_ACCOUNT_NAME, anAccountName); try { loadUserByAccountName(userBag); Hashtable<String, String> environmentalVariables = new Hashtable<String, String>(); environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE); environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null)); environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid"); environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environmentalVariables.put(Context.SECURITY_PRINCIPAL, userBag.getValueAsString(LDAP_DISTINGUISHED_NAME)); environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword); environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore")); environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple")); LdapContext ldapContext = new InitialLdapContext(environmentalVariables, null); ldapContext.close(); isValid = true; } catch (Exception ignored) { } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return isValid; }
From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java
private void authenticateWithoutTlsExtension(String userDN, String password) throws AuthenticationException { 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); env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, password); try {//from w w w.j a v a 2 s . com // Create initial context Context ctx = new InitialDirContext(env); ctx.close(); logger.debug("Authentication successful for {}", userDN); } catch (NamingException e) { throw new AuthenticationException("Error validating LDAP user", e); } }