List of usage examples for javax.naming Context SECURITY_CREDENTIALS
String SECURITY_CREDENTIALS
To view the source code for javax.naming Context SECURITY_CREDENTIALS.
Click Source Link
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
/** * Attempts to authenticate user credentials with the LDAP server * //from w w w . j a va2s. c o m * @param username * a username * @param password * a password * @param dn * if precise dn known, otherwise should be empty string * @return <code>true</code> if authentication was successful, * <code>false</code> otherwise */ private boolean bind(String username, String password) { try { String principal = String.format("%s=%s,%s", idAttr, username, baseDn); env.put(Context.SECURITY_PRINCIPAL, principal); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = new InitialDirContext(env); ctx.lookup(principal); ctx.close(); return true; } catch (NamingException ne) { log.warn("Failed LDAP lookup doAuthenticate", ne); } return false; }
From source file:ldap.LdapApi.java
/** * open the directory connection./*from ww w .j a v a2s .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; }
From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java
private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException { LdapContext ctx = null;//w ww. j a v a 2 s. com 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.olat.ldap.LDAPLoginManagerImpl.java
/** * Connect to LDAP with the User-Name and Password given as parameters Configuration: LDAP URL = olatextconfig.xml (property=ldapURL) LDAP Base = olatextconfig.xml * (property=ldapBase) LDAP Attributes Map = olatextconfig.xml (property=userAttrs) * /*w w w . j av a 2s .c o m*/ * @param uid The users LDAP login name (can't be null) * @param pwd The users LDAP password (can't be null) * @return After successful bind Attributes otherwise NULL * @throws NamingException */ public Attributes bindUser(final String uid, final String pwd, final LDAPError errors) { // get user name, password and attributes final String ldapUrl = LDAPLoginModule.getLdapUrl(); final String[] userAttr = LDAPLoginModule.getUserAttrs(); if (uid == null || pwd == null) { if (isLogDebugEnabled()) { logDebug("Error when trying to bind user, missing username or password. Username::" + uid + " pwd::" + pwd); } errors.insert("Username and password must be selected"); return null; } final LdapContext ctx = bindSystem(); if (ctx == null) { errors.insert("LDAP connection error"); return null; } final String userDN = searchUserDN(uid, ctx); if (userDN == null) { logInfo("Error when trying to bind user with username::" + uid + " - user not found on LDAP server" + (LDAPLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider" : "")); errors.insert("Username or password incorrect"); return null; } // Ok, so far so good, user exists. Now try to fetch attributes using the // users credentials final Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, pwd); if (LDAPLoginModule.isSslEnabled()) { enableSSL(env); } try { final Control[] connectCtls = new Control[] {}; final LdapContext userBind = new InitialLdapContext(env, connectCtls); final Attributes attributes = userBind.getAttributes(userDN, userAttr); userBind.close(); return attributes; } catch (final AuthenticationException e) { logInfo("Error when trying to bind user with username::" + uid + " - invalid LDAP password"); errors.insert("Username or password incorrect"); return null; } catch (final NamingException e) { logError("NamingException when trying to get attributes after binding user with username::" + uid, e); errors.insert("Username or password incorrect"); return null; } }
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Checks whether a user element exists, based on its username value. * @param username/*from w ww. j a v a 2 s .c o m*/ * User name. * @return <code>true</code> if the user can be looked up through JNDI, * otherwise <code>false</code>. * @throws BackendException * If there is a problem accessing the backend. */ public final boolean userExists(final String username) throws BackendException { // Sanity checks. if ((username == null) || (username.length() == 0)) return false; // The search pattern. String pattern = usernameAttribute + '=' + username; // Go through all references. InitialLdapContext ldap = null; for (int i = 0; i < myReferences.length; i++) { String[] references = myReferences[i].getReferences(); final String[] usernames = myReferences[i].getUsernames(); final String[] passwords = myReferences[i].getPasswords(); for (int j = 0; j < references.length; j++) { try { // Context for this reference. try { ldap = connect(references[j]); } catch (NamingException e) { // Connection failed, but we might have other sources. log.logWarn("Unable to access the backend on '" + references[j] + "' to verify existence of '" + username + "': " + e.getClass().getName(), mySessionTicket, e); continue; } // Anonymous search or not? ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); if ((usernames[j].length() == 0) && (passwords[j].length() > 0)) log.logWarn("Search username is empty but search password is not - possible index problem", mySessionTicket); else if ((passwords[j].length() == 0) && (usernames[j].length() > 0)) log.logWarn("Search password is empty but search username is not - possible index problem", mySessionTicket); else if ((passwords[j].length() == 0) && (usernames[j].length() == 0)) { log.logDebug("Anonymous search for user element DN on " + references[j], mySessionTicket); ldap.removeFromEnvironment(Context.SECURITY_AUTHENTICATION); } else log.logDebug("Non-anonymous search to verify existence of '" + username + "' on " + references[j], mySessionTicket); ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, usernames[j]); ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, passwords[j]); // Search this reference. if (ldapSearch(ldap, pattern) != null) return true; } catch (NamingException e) { // Unable to connect, but we might have other sources. log.logWarn("Unable to access the backend on '" + references[j] + "' to verify existence of '" + username + "': " + e.getClass().getName(), mySessionTicket, e); continue; } finally { // Close the LDAP connection. if (ldap != null) { try { ldap.close(); } catch (NamingException e) { // Ignored. log.logWarn("Unable to close the backend connection to '" + references[j] + "': " + e.getClass().getName(), mySessionTicket, e); } } } } } // Still no match. return false; }
From source file:com.springsource.insight.plugin.ldap.LdapOperationCollectionAspectTestSupport.java
protected static final Hashtable<String, Object> createEnvironment() { Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_PRINCIPAL, LDAP_USERNAME); env.put(Context.SECURITY_CREDENTIALS, LDAP_PASSWORD); return env;/*from w ww . j a v a 2s .c o m*/ }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
public void login(String userid, String password) throws AuthenticationException { try {/*from www. jav a2 s .com*/ LDAPAccount user = (LDAPAccount) getUser(userid); if (user == null) { throw new AuthenticationException(userid + " is not found."); } Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, this.connectionURL); env.put("java.naming.ldap.version", "3"); env.put(Context.SECURITY_PRINCIPAL, user.getDn()); env.put(Context.SECURITY_CREDENTIALS, password); new InitialDirContext(env); } catch (NamingException e) { throw new AuthenticationException(e); } }
From source file:org.apache.synapse.transport.jms.JMSUtils.java
/** * Set JNDI properties and any other connection factory parameters to the connection factory * passed in, looing at the parameter in axis2.xml * @param param the axis parameter that holds the connection factory settings * @param jmsConFactory the JMS connection factory to which the parameters should be applied *//*from ww w . ja va 2 s . c om*/ public static void setConnectionFactoryParameters(Parameter param, JMSConnectionFactory jmsConFactory) { ParameterIncludeImpl pi = new ParameterIncludeImpl(); try { pi.deserializeParameters((OMElement) param.getValue()); } catch (AxisFault axisFault) { log.error("Error reading parameters for JMS connection factory" + jmsConFactory.getName(), axisFault); } Iterator params = pi.getParameters().iterator(); while (params.hasNext()) { Parameter p = (Parameter) params.next(); if (JMSConstants.CONFAC_TYPE.equals(p.getName())) { String connectionFactoryType = (String) p.getValue(); jmsConFactory.setConnectionFactoryType(connectionFactoryType); } else if (JMSConstants.RECONNECT_TIMEOUT.equals(p.getName())) { String strTimeout = (String) p.getValue(); int reconnectTimeoutSeconds = Integer.parseInt(strTimeout); long reconnectTimeoutMillis = reconnectTimeoutSeconds * 1000; jmsConFactory.setReconnectTimeout(reconnectTimeoutMillis); } else if (Context.INITIAL_CONTEXT_FACTORY.equals(p.getName())) { jmsConFactory.addJNDIContextProperty(Context.INITIAL_CONTEXT_FACTORY, (String) p.getValue()); } else if (Context.PROVIDER_URL.equals(p.getName())) { jmsConFactory.addJNDIContextProperty(Context.PROVIDER_URL, (String) p.getValue()); } else if (Context.SECURITY_PRINCIPAL.equals(p.getName())) { jmsConFactory.addJNDIContextProperty(Context.SECURITY_PRINCIPAL, (String) p.getValue()); } else if (Context.SECURITY_CREDENTIALS.equals(p.getName())) { jmsConFactory.addJNDIContextProperty(Context.SECURITY_CREDENTIALS, (String) p.getValue()); } else if (JMSConstants.CONFAC_JNDI_NAME_PARAM.equals(p.getName())) { jmsConFactory.setConnFactoryJNDIName((String) p.getValue()); jmsConFactory.addJNDIContextProperty(JMSConstants.CONFAC_JNDI_NAME_PARAM, (String) p.getValue()); } } }
From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java
/** * Gets and returns the entries from the server. * //from w ww . j a v a2 s . c o m * @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: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 ww .j a 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; } }