List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:eu.europa.ec.markt.dss.validation.crl.OnlineCRLSource.java
/** * Downloads a CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com * * @throws CertificateException// w w w . j ava 2 s . c o m * @throws CRLException */ private static X509CRL downloadCRLFromLDAP_(final String ldapURL) throws DSSException { 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); try { final DirContext ctx = new InitialDirContext(env); final Attributes attributes = ctx.getAttributes(""); final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary"); final byte[] val = (byte[]) attribute.get(); if (val == null || val.length == 0) { throw new DSSException("Can not download CRL from: " + ldapURL); } final InputStream inStream = new ByteArrayInputStream(val); return DSSUtils.loadCRL(inStream); } catch (Exception e) { LOG.warning(e.getMessage()); e.printStackTrace(); } return null; }
From source file:org.wso2.appcloud.core.DomainMappingManager.java
/** * Resolve CNAME and A records for the given {@code hostname}. * * @param domain hostname to be resolved. * @param environmentConfigs environment configuration * @return {@link com.google.common.collect.Multimap} of resolved dns entries. This {@link com.google.common.collect.Multimap} will contain the resolved * "CNAME" and "A" records from the given {@code hostname} * @throws AppCloudException if error occurred while the operation */// w ww . ja v a2s .com public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs) throws AppCloudException, NamingException { // result mutimap of dns records. Contains the cname and records resolved by the given hostname // ex: CNAME => foo.com,bar.com // A => 192.1.2.3 , 192.3.4.5 Multimap<String, String> dnsRecordsResult = ArrayListMultimap.create(); Attributes dnsRecords; boolean isARecordFound = false; boolean isCNAMEFound = false; try { if (log.isDebugEnabled()) { log.debug("DNS validation: resolving DNS for " + domain + " " + "(A/CNAME)"); } DirContext context = new InitialDirContext(environmentConfigs); String[] dnsRecordsToCheck = new String[] { DNS_A_RECORD, DNS_CNAME_RECORD }; dnsRecords = context.getAttributes(domain, dnsRecordsToCheck); } catch (NamingException e) { String msg = "DNS validation: DNS query failed for: " + domain + ". Error occurred while configuring " + "directory context."; log.error(msg, e); throw new AppCloudException(msg, e); } try { // looking for for A records Attribute aRecords = dnsRecords.get(DNS_A_RECORD); if (aRecords != null && aRecords.size() > 0) { // if an A record exists NamingEnumeration aRecordHosts = aRecords.getAll(); // get all resolved A entries String aHost; while (aRecordHosts.hasMore()) { isARecordFound = true; aHost = (String) aRecordHosts.next(); dnsRecordsResult.put(DNS_A_RECORD, aHost); if (log.isDebugEnabled()) { log.debug("DNS validation: A record found: " + aHost); } } } // looking for CNAME records Attribute cnameRecords = dnsRecords.get(DNS_CNAME_RECORD); if (cnameRecords != null && cnameRecords.size() > 0) { // if CNAME record exists NamingEnumeration cnameRecordHosts = cnameRecords.getAll(); // get all resolved CNAME entries for hostname String cnameHost; while (cnameRecordHosts.hasMore()) { isCNAMEFound = true; cnameHost = (String) cnameRecordHosts.next(); if (cnameHost.endsWith(".")) { // Since DNS records are end with "." we are removing it. // For example real dns entry for www.google.com is www.google.com. cnameHost = cnameHost.substring(0, cnameHost.lastIndexOf('.')); } dnsRecordsResult.put(DNS_CNAME_RECORD, cnameHost); if (log.isDebugEnabled()) { log.debug("DNS validation: recurring on CNAME record towards host " + cnameHost); } dnsRecordsResult.putAll(resolveDNS(cnameHost, environmentConfigs)); // recursively resolve cnameHost } } if (!isARecordFound && !isCNAMEFound && log.isDebugEnabled()) { log.debug("DNS validation: No CNAME or A record found for domain: '" + domain); } return dnsRecordsResult; } catch (NamingException ne) { String msg = "DNS validation: DNS query failed for: " + domain + ". Provided domain: " + domain + " might be a " + "non existing domain."; // we are logging this as warn messages since this is caused, due to an user error. For example if the // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the // time of adding the url), then url validation will fail but it is not an system error log.warn(msg, ne); throw new NamingException(msg); } }
From source file:org.gbif.portal.registration.LDAPUtils.java
/** * Get LDAP context./* w w w . j a v a 2s .com*/ * @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.hs.mail.security.login.JndiLoginModule.java
@SuppressWarnings("unchecked") protected DirContext open() throws NamingException { if (context == null) { try {//from w ww .j a v a 2 s. c o m // Set up the environment for creating the initial context Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory); if (StringUtils.isNotEmpty(username)) { env.put(Context.SECURITY_PRINCIPAL, username); } if (StringUtils.isNotEmpty(password)) { env.put(Context.SECURITY_CREDENTIALS, password); } env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_AUTHENTICATION, authentication); context = new InitialDirContext(env); } catch (NamingException e) { throw e; } } return context; }
From source file:com.konakart.bl.LDAPMgrCore.java
/** * Called if the LDAP module is installed and active. This method should return: * <ul>//from ww w. ja va2 s. c o m * <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:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns <code>true</code> if the supplied id is found in the JNDI storage. * @see IStorage#exists(java.lang.String) */// ww w. jav a2 s. c o m public boolean exists(String id) throws UserException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; boolean bReturn = false; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); bReturn = oNamingEnumeration.hasMore(); } catch (InvalidSearchFilterException e) { _logger.error("Wrong filter: " + searchFilter); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.debug("User unknown, naming exception. query: " + searchFilter, e); return false; //user unknown } } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not verify if user exists: " + id, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return bReturn; }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Creates a DirContext with the applications configuration settings. * @return a DirContext/* ww w . j av a 2 s.c o 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); }
From source file:tools.pki.gbay.crypto.keys.validation.CertificateRevocationList.java
/** * Downloads a CRL from given LDAP url, e.g. * ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com * @throws IOException //w ww . j a v a 2s . c o m */ @SuppressWarnings("rawtypes") private static X509CRL downloadCRLFromLDAP(String ldapURL) throws CertificateException, NamingException, CRLException, CryptoException, IOException { Map<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapURL); DirContext ctx = new InitialDirContext((Hashtable) env); Attributes avals = ctx.getAttributes(""); Attribute aval = avals.get("certificateRevocationList;binary"); byte[] val = (byte[]) aval.get(); if ((val == null) || (val.length == 0)) { throw new CryptoException("Can not download CRL from: " + ldapURL); } else { return fromByteArray(val); } }
From source file:org.pegadi.server.user.LDAPUserServerImpl.java
/** * Can probably be done more elegant too. * * @param userDN real dn to the user.// www. j a v a2 s .com * @param password the user's password * @return */ public boolean checkAuthentication(String userDN, String password) { if (password.trim().equals("")) return false; DirContext ctx2 = null; try { // See if the user authenticates. Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url + "/" + ldapBaseDN); env.put(Context.SECURITY_AUTHENTICATION, auth); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, password); env.put("com.sun.jndi.ldap.connect.timeout", "10000"); // Specify timeout to be 10 seconds, only on non SSL since SSL connections // break with a timeout. ctx2 = new InitialDirContext(env); log.info("Successfully logged in... " + userDN); } catch (Exception e) { log.error("Exception during login", e); return false; } finally { try { ctx2.close(); } catch (NamingException ignore) { } } return true; }
From source file:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java
private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind, boolean recursiveSearch) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl); env.put(Context.PROVIDER_URL, provUrl); if (StringUtils.isNotEmpty(cf.getUsername())) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, cf.getUsername()); env.put(Context.SECURITY_CREDENTIALS, cf.getPassword()); } else {//from w w w . ja v a 2 s. c om env.put(Context.SECURITY_AUTHENTICATION, "none"); } DirContext ctx = null; try { try { ctx = new InitialDirContext(env); } catch (CommunicationException e) { log.info("Cannot create constructor for DirContext (" + e.getMessage() + "], will try again with dummy SocketFactory"); env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName()); ctx = new InitialLdapContext(env, null); } Attribute attrs = ctx.getAttributes("").get("member"); if (attrs != null) { boolean found = false; for (int i = 0; i < attrs.size() && !found; i++) { String dnFound = (String) attrs.get(i); if (dnFound.equalsIgnoreCase(dnFind)) { found = true; } else { if (recursiveSearch) { found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch); } } } return found; } } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { log.warn("Exception closing DirContext", e); } } } return false; }