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:org.exoplatform.services.organization.DummyLDAPServiceImpl.java
public DummyLDAPServiceImpl() throws Exception { File workingDirectory = new File("target/working-server"); workingDirectory.mkdirs();//from ww w. j av a 2 s. com doDelete(workingDirectory); // Initialize the LDAP service service = new DefaultDirectoryService(); service.setWorkingDirectory(workingDirectory); // first load the schema initSchemaPartition(); // then the system partition // this is a MANDATORY partition Partition systemPartition = addPartition("system", ServerDNConstants.SYSTEM_DN); service.setSystemPartition(systemPartition); // Disable the ChangeLog system service.getChangeLog().setEnabled(false); // Create a new partition Partition partition = addPartition("eXoTestPartition", "dc=exoplatform,dc=org"); // Index some attributes on the partition addIndex(partition, "objectClass", "ou", "uid"); service.setShutdownHookEnabled(false); service.startup(); // Inject the eXo root entry if it does not already exist if (!service.getAdminSession().exists(partition.getSuffixDn())) { DN dnExo = new DN("dc=exoplatform,dc=org"); ServerEntry entryExo = service.newEntry(dnExo); entryExo.add("objectClass", "top", "domain", "extensibleObject"); entryExo.add("dc", "exoplatform"); service.getAdminSession().add(entryExo); } port = AvailablePortFinder.getNextAvailable(1024); server = new LdapServer(); server.setTransports(new TcpTransport(port)); server.setDirectoryService(service); server.start(); // server launched and configured // configuration of client side env.put(DirectoryService.JNDI_KEY, service); env.put(Context.PROVIDER_URL, ""); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName()); // Add the new schema needed for COR-293 addNewSchema(); }
From source file:org.gbif.portal.registration.LDAPUtils.java
/** * Get LDAP context.// w w w. jav a 2s . c o m * @param url * @return * @throws NamingException */ public DirContext getContext(String url) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, url); env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); env.put(Context.SECURITY_AUTHENTICATION, authenticationType); env.put(Context.SECURITY_PRINCIPAL, securityPrincipal); env.put(Context.SECURITY_CREDENTIALS, securityCredentials); DirContext ctx = new InitialDirContext(env); return ctx; }
From source file:com.konakart.bl.LDAPMgrCore.java
/** * Called if the LDAP module is installed and active. This method should return: * <ul>// w ww .j ava 2 s . c om * <li>A negative number in order for the login attempt to fail. The KonaKart login() method * will return a null sessionId</li> * <li>Zero to signal that this method is not implemented. The KonaKart login() method will * perform the credential check.</li> * <li>A positive number for the login attempt to pass. The KonaKart login() will not check * credentials, and will log in the customer, returning a valid session id.</li> * </ul> * This method may need to be modified slightly depending on the structure of your LDAP. The * example works when importing the exampleData.ldif file in the LDAP module jar: * * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/> * objectclass: inetOrgPerson<br/> * cn: Robert Smith<br/> * cn: Robert J Smith<br/> * cn: bob smith<br/> * sn: smith<br/> * uid: rjsmith<br/> * userpassword: rJsmitH<br/> * carlicense: HISCAR 123<br/> * homephone: 555-111-2222<br/> * mail: r.smith@example.com<br/> * mail: rsmith@example.com<br/> * mail: bob.smith@example.com<br/> * description: swell guy<br/> * * The code attempts to connect to LDAP using the username, password and URL in the * configuration variables set when the module was installed through the admin app.<br/> * * After having connected, the person object is searched for using the email address of the * user. If found we use the "cn" attribute and the password of the user to attempt to bind to * LDAP. If the bind is successful, we return a positive number which means that authentication * was successful. * * @param emailAddr * The user name required to log in * @param password * The log in password * @return Returns an integer * @throws Exception */ public int checkCredentials(String emailAddr, String password) throws Exception { DirContext ctx = null; try { Hashtable<String, String> environment = new Hashtable<String, String>(); if (log.isDebugEnabled()) { log.debug("LDAP connection URL = " + url); log.debug("LDAP user name = " + ldapUserName); log.debug("LDAP person object distinguished name (DN) = " + personDN); } if (ldapUserName == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set."); } if (ldapPassword == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set."); } if (url == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set."); } if (personDN == null) { throw new KKException( "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set."); } environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environment.put(Context.SECURITY_AUTHENTICATION, "simple"); environment.put(Context.PROVIDER_URL, url); environment.put(Context.SECURITY_PRINCIPAL, ldapUserName); environment.put(Context.SECURITY_CREDENTIALS, ldapPassword); /* * connect to LDAP using the credentials and connection string from the configuration * variables */ try { ctx = new InitialDirContext(environment); } catch (Exception e) { log.error("Cannot connect to LDAP", e); return -1; } /* Specify the search filter on the eMail address */ String filter = "(mail=" + emailAddr + ")"; /* * limit returned attributes to those we care about. In this case we only require the * "cn" attribute which we will use to attempt to bind the user in order to validate his * password */ String[] attrIDs = { "cn" }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); /* Search for objects using filter and controls */ NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls); /* close the connection */ ctx.close(); if (answer == null || !answer.hasMore()) { return -1; } SearchResult sr = answer.next(); Attributes attrs = sr.getAttributes(); String cn = attrs.get("cn").toString(); if (log.isDebugEnabled()) { log.debug("cn of user with eMail (" + emailAddr + ") is " + cn); } /* * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture * just the first entry */ if (cn != null) { if (cn.contains(",")) { cn = cn.split(",")[0]; if (cn.contains(":")) { cn = cn.split(":")[1]; } } else if (cn.contains(":")) { cn = cn.split(":")[1]; } } if (log.isDebugEnabled()) { log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn); } /* Now we try to bind as the user */ String userName = "cn=" + cn + "," + personDN; if (log.isDebugEnabled()) { log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName); } /* Bind as the user */ environment.put(Context.SECURITY_PRINCIPAL, userName); environment.put(Context.SECURITY_CREDENTIALS, password); try { ctx = new InitialDirContext(environment); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Could not bind user " + userName); } return -1; } ctx.close(); if (log.isDebugEnabled()) { log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP"); } return 1; } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { log.error("Received an exception while closing the LDAP DirContext", e); } } } }
From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.LdapCommentAuthenticator.java
public boolean authenticate(HttpServletRequest request) { boolean validUser = false; LdapContext context = null;// w ww . j av a 2 s .c om String ldapDc = WebloggerConfig.getProperty("comment.authenticator.ldap.dc"); String ldapOu = WebloggerConfig.getProperty("comment.authenticator.ldap.ou"); String ldapPort = WebloggerConfig.getProperty("comment.authenticator.ldap.port"); String ldapHost = WebloggerConfig.getProperty("comment.authenticator.ldap.host"); String ldapSecurityLevel = WebloggerConfig.getProperty("comment.authenticator.ldap.securityLevel"); boolean rollerPropertiesValid = validateRollerProperties(ldapDc, ldapOu, ldapPort, ldapHost); String ldapUser = request.getParameter("ldapUser"); String ldapPass = request.getParameter("ldapPass"); boolean userDataValid = validateUsernamePass(ldapUser, ldapPass); if (rollerPropertiesValid && userDataValid) { try { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); if (ldapSecurityLevel != null && (ldapSecurityLevel.equalsIgnoreCase("none") || ldapSecurityLevel.equalsIgnoreCase("simple") || ldapSecurityLevel.equalsIgnoreCase("strong"))) { env.put(Context.SECURITY_AUTHENTICATION, ldapSecurityLevel); } env.put(Context.SECURITY_PRINCIPAL, getQualifedDc(ldapDc, ldapOu, ldapUser)); env.put(Context.SECURITY_CREDENTIALS, ldapPass); env.put(Context.PROVIDER_URL, "ldap://" + ldapHost + ":" + ldapPort); context = new InitialLdapContext(env, null); validUser = true; LOG.info("LDAP Authentication Successful. user: " + ldapUser); } catch (Exception e) { // unexpected LOG.error(e); } finally { if (context != null) { try { context.close(); } catch (NamingException e) { LOG.error(e); } } } } return validUser; }
From source file:org.kitodo.production.services.data.LdapServerService.java
private Hashtable<String, String> initializeWithLdapConnectionSettings(LdapServer ldapServer) { Hashtable<String, String> env = new Hashtable<>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapServer.getUrl()); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, ldapServer.getManagerLogin()); String encryptedManagerPassword = ldapServer.getManagerPassword(); String decryptedManagerPassword = passwordEncoder.decrypt(encryptedManagerPassword); env.put(Context.SECURITY_CREDENTIALS, decryptedManagerPassword); if (ldapServer.isUseSsl()) { String keystorepath = ldapServer.getKeystore(); String keystorepasswd = ldapServer.getKeystorePassword(); // add all necessary certificates first loadCertificates(keystorepath, keystorepasswd, ldapServer); // set properties, so that the current keystore is used for SSL System.setProperty("javax.net.ssl.keyStore", keystorepath); System.setProperty("javax.net.ssl.trustStore", keystorepath); System.setProperty("javax.net.ssl.keyStorePassword", keystorepasswd); env.put(Context.SECURITY_PROTOCOL, "ssl"); }// w w w .j a va2s. com return env; }
From source file:org.andromda.timetracker.test.EJB3Container.java
private static Hashtable<String, String> getInitialContextProperties(String principal, String credential) { Hashtable<String, String> props = new Hashtable<String, String>(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory"); props.put(Context.SECURITY_PRINCIPAL, principal); props.put(Context.SECURITY_CREDENTIALS, credential); return props; }
From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java
/** * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String) */// w ww. j a v a 2 s .c om protected boolean validatePassword(String inputPassword, String expectedPassword) { // Load our LDAP specific properties Properties env = getProperties(); // Load the BaseDN String baseDN = (String) options.get("BaseDN"); if (baseDN == null) { // If the BaseDN is not specified, log an error and refuse the login attempt log.info("BaseDN is not set, refusing login"); return false; } // Many LDAP servers allow bind's with an emtpy password. We will deny all requests with empty passwords if ((inputPassword == null) || inputPassword.equals("")) { log.debug("Empty password, refusing login"); return false; } // Load the LoginProperty String loginProperty = (String) options.get("LoginProperty"); if (loginProperty == null) { // Use the default loginProperty = "cn"; } // Load any search filter String searchFilter = (String) options.get("Filter"); // Find the user that is calling us String userName = getUsername(); // Load any information we may need to bind String bindDN = (String) options.get("BindDN"); String bindPW = (String) options.get("BindPW"); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); // Add the search filter if specified. This only allows for a single search filter.. i.e. foo=bar. String filter; if ((searchFilter != null) && (searchFilter.length() != 0)) { filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))"; } else { filter = "(" + loginProperty + "=" + userName + ")"; } log.debug("Using LDAP filter=" + filter); // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration answer = ctx.search(baseDNs[x], filter, searchControls); boolean ldapApiNpeFound = false; if (!answer.hasMoreElements()) {//BZ:582471- ldap api bug log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]); // Nothing found for this DN, move to the next one if we have one. continue; } // We use the first match SearchResult si = (SearchResult) answer.next(); // Construct the UserDN String userDN = si.getName() + "," + baseDNs[x]; ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inputPassword); ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); //if successful then verified that user and pw are valid ldap credentials ctx.reconnect(null); return true; } // If we try all the BaseDN's and have not found a match, return false return false; } catch (Exception e) { log.info("Failed to validate password: " + e.getMessage()); return false; } }
From source file:org.sonar.plugins.ldap.LdapContextFactory.java
private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling) throws NamingException { final InitialLdapContext ctx; if (startTLS) { // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed. Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.REFERRAL, DEFAULT_REFERRAL); // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid "bind" operation prior to StartTLS: ctx = new InitialLdapContext(env, null); // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); try {//w w w .jav a 2 s.co m tls.negotiate(); } catch (IOException e) { NamingException ex = new NamingException("StartTLS failed"); ex.initCause(e); throw ex; } // Explicitly initiate "bind" operation: ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials); ctx.reconnect(null); } else { ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null); } return ctx; }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
public boolean findUserByEmail(UserEdit edit, String email) { env.put(Context.SECURITY_PRINCIPAL, ""); env.put(Context.SECURITY_CREDENTIALS, ""); String filter = "(&(objectclass=person)(mail=" + escapeSearchFilterTerm(email) + "))"; return getUserInf(edit, filter); }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Creates a DirContext with the applications configuration settings. * @return a DirContext/*from ww w .j a v a 2 s .co m*/ * @throws NamingException if an exception is thrown * @since 1.4.0 */ public DirContext createDirContext() throws NamingException { final Hashtable<String, String> env = new Hashtable<>(); env.put(Context.SECURITY_PRINCIPAL, BIND_USERNAME); env.put(Context.SECURITY_CREDENTIALS, BIND_PASSWORD); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); if (IS_LDAP_SSLTLS) { env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory"); } return new InitialDirContext(env); }