List of usage examples for javax.naming.directory InitialDirContext InitialDirContext
public InitialDirContext(Hashtable<?, ?> environment) throws NamingException
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
/** * Se conecta a la url indicada y se descarga las crls. No se esta usando * *******************!!! En desarrollo, no funciona * /*from w w w .j av a 2 s. c om*/ * @param hostURL * @return * @throws CRLException * No se ha podido recuperar el listado * @throws CertificateParsingException */ @SuppressWarnings("unchecked") private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509) throws CRLException, CertificateParsingException { // ************************ // recupero las propiedades para realizar la busqueda en LDAP. // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1} Map<String, String> propiedades = new HashMap<String, String>(); try { log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: " + certificadoX509.getIssuerDN()); // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds // segun el RFC 3280 seccin 4.2.1.14) byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS); if (val1 == null) { log.debug(" El certificado NO tiene punto de distribucin de CRL "); } else { ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1)); DERObject derObj = oAsnInStream.readObject(); DEROctetString dos = (DEROctetString) derObj; byte[] val2 = dos.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2)); DERObject derObj2 = oAsnInStream2.readObject(); X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades); } } catch (Exception e) { e.printStackTrace(); throw new CertificateParsingException(e.toString()); } // comprobamos la configuracin if (isSomeFNMTValorNull()) { throw new CRLException( "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :" + Constantes.CONEXION_LDAP_CRL_FNMT); } String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN(); log.debug("Buscando en el LDAP " + CN); // ********************************************** // Nos conectamos al LDAP para recuperar la CRLs. Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, fnmtLDAPHostURL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal); env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial); env.put(Context.REFERRAL, "follow"); try { DirContext ctx = new InitialDirContext(env); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls)); log.debug("Se ha logrado conectar al LDAP"); if (namings.hasMore()) { log.debug("Recuperando el contenido de la CRLs"); // recupero el resultado SearchResult resultado = ((SearchResult) namings.next()); // recupero todos los atributos del resultado Attributes avals = resultado.getAttributes(); // recupero los bytes. byte[] bytes; if ((avals.get("certificateRevocationList;binary")) != null) { log.debug("Atributos deben estar en binario"); Attribute atributo = (avals.get("certificateRevocationList;binary")); bytes = ((byte[]) atributo.get()); } else { log.debug("Atributos en exadecimal En Hexadecimal"); Attribute atributo = (avals.get("certificateRevocationList")); bytes = ((byte[]) atributo.get()); log.debug("Por implementar"); } if (bytes != null) { ByteArrayInputStream io = new ByteArrayInputStream(bytes); return io; } } } catch (NamingException e) { log.error("No se puede conectar al LDAP!!", e); } return null; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Set next free uidNumber./*from w w w .ja v a 2 s . c o m*/ */ private void setNextUidNumber() { Hashtable<String, String> env = getLdapConnectionSettings(); env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); DirContext ctx; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId")); Attribute la = attrs.get("uidNumber"); String oldValue = (String) la.get(0); int bla = Integer.parseInt(oldValue) + 1; BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla)); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu); ctx.modifyAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"), mods); ctx.close(); } catch (NamingException e) { logger.error(e); } }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private DirContext connect(Config config) { try {/* w ww. j av a 2 s . co m*/ Properties env = new Properties(); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, config.getBindDN()); env.put(Context.SECURITY_CREDENTIALS, config.getPassword()); env.put(LDAP_VERSION, DEFAULT_LDAP_VERSION); env.put(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_CTX); env.put(Context.PROVIDER_URL, "ldap://" + config.getHost() + ":" + config.getPort()); if (config.getReferral() != null) { env.put(Context.REFERRAL, config.getReferral()); } if (config.getProtocol() != null) env.put(Context.SECURITY_PROTOCOL, config.getProtocol()); env.put("com.sun.jndi.ldap.connect.pool", "true"); return new InitialDirContext(env); } catch (NamingException e) { throw new OXFException("LDAP connect Failed", e); } }
From source file:edu.lafayette.metadb.model.userman.UserManDAO.java
/** * Perform LDAP authentication for a user. * @param userName The username to authenticate. * @param password The password to authenticate. * @return true if the user was successfully authenticated by LDAP, false otherwise. *///from w w w . ja v a 2 s .c om private static boolean authLDAP(String userName, String password) { String searchUser = Global.LDAP_BROWSE_USERNAME; String searchPassword = Global.LDAP_BROWSE_PASSWORD; String dn = null; if (searchUser.equals("") || searchPassword.equals("") || searchUser == null || searchPassword == null) dn = Global.LDAP_ID + "=" + userName + "," + Global.LDAP_CONTEXT; else { dn = getDN(searchUser, searchPassword, userName); // Check a DN was found if ((dn == null) || (dn.trim().equals(""))) { //MetaDbHelper.note("Hierarchical LDAP Authentication Error: No DN found for user "+userName); return false; } } boolean success = false; // Set up environment for creating initial context Hashtable<String, String> env = new Hashtable<String, String>(); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL); // Authenticate env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple"); env.put(javax.naming.Context.SECURITY_PRINCIPAL, dn); env.put(javax.naming.Context.SECURITY_CREDENTIALS, password); env.put(javax.naming.Context.AUTHORITATIVE, "true"); env.put(javax.naming.Context.REFERRAL, "follow"); DirContext ctx = null; try { // Try to bind ctx = new InitialDirContext(env); success = true; //MetaDbHelper.note("User "+userName+" logged in with LDAP"); //MetaDbHelper.note("Context name: "+ctx.getNameInNamespace()); //MetaDbHelper.note(ctx.toString()); } catch (NamingException e) { MetaDbHelper.note("Error: Failed to authenticate " + userName + ".\n" + e); success = false; } finally { // Close the context when we're done try { if (ctx != null) ctx.close(); //MetaDbHelper.note("LDAP connection closed"); } catch (NamingException e) { MetaDbHelper.logEvent(e); //MetaDbHelper.note("Error: Failed to establish context."); } } return success; }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
/** * Tries to find the value of the given attribute. Note that this method * only uses the first search result.//from w w w . ja va2s .co m * * @param username * a username * @param attrName * the name of the attribute to find * @return the value of the attribute, or an empty string */ public String getAttr(String username, String attrName) { String val = ""; try { DirContext dc = new InitialDirContext(env); NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc); if (ne.hasMore()) { val = getAttrValue(attrName, ne.next()); } ne.close(); dc.close(); } catch (NamingException ne) { log.warn("Failed LDAP lookup getAttr", ne); log.warn("username:", username); log.warn("attrName:", attrName); } log.trace(String.format("getAttr search result: %s", val)); return val; }
From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
protected DirContext open() throws NamingException { if (context != null) { return context; }//from w w w.ja v a 2s . c o m try { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); if (connectionUsername != null || !"".equals(connectionUsername)) { env.put(Context.SECURITY_PRINCIPAL, connectionUsername); } if (connectionPassword != null || !"".equals(connectionPassword)) { env.put(Context.SECURITY_CREDENTIALS, connectionPassword); } env.put(Context.SECURITY_PROTOCOL, connectionProtocol == null ? "" : connectionProtocol); env.put(Context.PROVIDER_URL, connectionURL == null ? "" : connectionURL); env.put(Context.SECURITY_AUTHENTICATION, authentication == null ? "" : authentication); context = new InitialDirContext(env); } catch (NamingException e) { log.error(e); throw e; } return context; }
From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java
public void afterPropertiesSet() throws Exception { logger.debug("after Properties Set"); // Check Anonymous bind Hashtable<String, String> env = new Hashtable<String, String>(authenticatedEnvironment.size()); env.putAll(authenticatedEnvironment); env.remove(Context.SECURITY_PRINCIPAL); env.remove(Context.SECURITY_CREDENTIALS); if (isSSLSocketFactoryRequired()) { KeyStore trustStore = initTrustStore(); AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName()); }/* w w w .j a v a2 s . c o m*/ try { new InitialDirContext(env); logger.warn("LDAP server supports anonymous bind " + env.get(Context.PROVIDER_URL)); } catch (javax.naming.AuthenticationException ax) { } catch (AuthenticationNotSupportedException e) { } catch (NamingException nx) { logger.error("Unable to connect to LDAP Server; check LDAP configuration", nx); return; } // Simple DN and password env = new Hashtable<String, String>(authenticatedEnvironment.size()); env.putAll(authenticatedEnvironment); env.put(Context.SECURITY_PRINCIPAL, "daftAsABrush"); env.put(Context.SECURITY_CREDENTIALS, "daftAsABrush"); if (isSSLSocketFactoryRequired()) { KeyStore trustStore = initTrustStore(); AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName()); } try { new InitialDirContext(env); throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL) + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported."); } catch (javax.naming.AuthenticationException ax) { logger.info("LDAP server does not fall back to anonymous bind for a string uid and password at " + env.get(Context.PROVIDER_URL)); } catch (AuthenticationNotSupportedException e) { logger.info("LDAP server does not fall back to anonymous bind for a string uid and password at " + env.get(Context.PROVIDER_URL)); } catch (NamingException nx) { logger.info("LDAP server does not support simple string user ids and invalid credentials at " + env.get(Context.PROVIDER_URL)); } // DN and password env = new Hashtable<String, String>(authenticatedEnvironment.size()); env.putAll(authenticatedEnvironment); env.put(Context.SECURITY_PRINCIPAL, "cn=daftAsABrush,dc=woof"); env.put(Context.SECURITY_CREDENTIALS, "daftAsABrush"); if (isSSLSocketFactoryRequired()) { KeyStore trustStore = initTrustStore(); AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName()); } try { new InitialDirContext(env); throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL) + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported."); } catch (javax.naming.AuthenticationException ax) { logger.info("LDAP server does not fall back to anonymous bind for a simple dn and password at " + env.get(Context.PROVIDER_URL)); } catch (AuthenticationNotSupportedException e) { logger.info("LDAP server does not fall back to anonymous bind for a simple dn and password at " + env.get(Context.PROVIDER_URL)); } catch (NamingException nx) { logger.info("LDAP server does not support simple DN and invalid password at " + env.get(Context.PROVIDER_URL)); } // Check more if we have a real principal we expect to work String principal = defaultEnvironment.get(Context.SECURITY_PRINCIPAL); if (principal != null) { // Correct principal invalid password env = new Hashtable<String, String>(authenticatedEnvironment.size()); env.putAll(authenticatedEnvironment); env.put(Context.SECURITY_PRINCIPAL, principal); env.put(Context.SECURITY_CREDENTIALS, "sdasdasdasdasd123123123"); if (isSSLSocketFactoryRequired()) { KeyStore trustStore = initTrustStore(); AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName()); } if (!checkedEnvs.contains(env)) { try { new InitialDirContext(env); throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL) + " falls back to use anonymous bind for a known principal if invalid security credentials are presented. This is not supported."); } catch (javax.naming.AuthenticationException ax) { logger.info( "LDAP server does not fall back to anonymous bind for known principal and invalid credentials at " + env.get(Context.PROVIDER_URL)); } catch (AuthenticationNotSupportedException e) { logger.info("LDAP server does not support the required authentication mechanism"); } catch (NamingException nx) { // already done } // Record this environment as checked so that we don't check it again on further restarts / other subsystem // instances checkedEnvs.add(env); } } }
From source file:org.apache.syncope.fit.core.reference.AbstractITCase.java
@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" }) protected InitialDirContext getLdapResourceDirContext(final String bindDn, final String bindPwd) throws NamingException { ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP); final Map<String, ConnConfProperty> ldapConnConf = connectorService.read(ldapRes.getConnector()) .getConfigurationMap();/* w w w . ja v a2 s . c o m*/ Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + ldapConnConf.get("host").getValues().get(0) + ":" + ldapConnConf.get("port").getValues().get(0) + "/"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDn == null ? ldapConnConf.get("principal").getValues().get(0) : bindDn); env.put(Context.SECURITY_CREDENTIALS, bindPwd == null ? ldapConnConf.get("credentials").getValues().get(0) : bindPwd); return new InitialDirContext(env); }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
/** * Tries to find the value(s) of the given attribute. Note that this method * uses all search results./*w ww. j a va2s . c o m*/ * * @param username * a username * @param attrName * the name of the attribute to find * @return a list of values for the attribute, or an empty list */ public List<String> getAllAttrs(String username, String attrName) { List<String> resultList = new ArrayList<String>(); try { DirContext dc = new InitialDirContext(env); NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc); while (ne.hasMore()) { resultList.add(getAttrValue(attrName, ne.next())); } ne.close(); dc.close(); } catch (NamingException ne) { log.warn("Failed LDAP lookup getAllAttrs" + username, ne); } log.trace("getAllAttrs search result: " + resultList); if (log.isTraceEnabled()) { log.trace("getAllAttrs search result: " + resultList); } return resultList; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * change password of given user, needs old password for authentication. * * @param inUser// www . ja v a 2 s .co m * User object * @param inOldPassword * String * @param inNewPassword * String * @return boolean about result of change */ public boolean changeUserPassword(User inUser, String inOldPassword, String inNewPassword) throws NoSuchAlgorithmException { MD4 digester = new MD4(); Hashtable<String, String> env = getLdapConnectionSettings(); if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) { env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); try { DirContext ctx = new InitialDirContext(env); /* * Encryption of password and Base64-Encoding */ MessageDigest md = MessageDigest.getInstance(ConfigCore.getParameter("ldap_encryption", "SHA")); md.update(inNewPassword.getBytes(StandardCharsets.UTF_8)); String digestBase64 = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8); ModificationItem[] mods = new ModificationItem[4]; /* * UserPasswort-Attribut ndern */ BasicAttribute userpassword = new BasicAttribute("userPassword", "{" + ConfigCore.getParameter("ldap_encryption", "SHA") + "}" + digestBase64); /* * LanMgr-Passwort-Attribut ndern */ BasicAttribute lanmgrpassword = null; try { lanmgrpassword = new BasicAttribute("sambaLMPassword", LdapUser.toHexString(LdapUser.lmHash(inNewPassword))); // TODO: Don't catch super class exception, make sure that // the password isn't logged here } catch (Exception e) { logger.error(e); } /* * NTLM-Passwort-Attribut ndern */ BasicAttribute ntlmpassword = null; try { byte hmm[] = digester.digest(inNewPassword.getBytes("UnicodeLittleUnmarked")); ntlmpassword = new BasicAttribute("sambaNTPassword", LdapUser.toHexString(hmm)); } catch (UnsupportedEncodingException e) { // TODO: Make sure that the password isn't logged here logger.error(e); } BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet", String.valueOf(System.currentTimeMillis() / 1000l)); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userpassword); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrpassword); mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmpassword); mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet); ctx.modifyAttributes(getUserDN(inUser), mods); // Close the context when we're done ctx.close(); return true; } catch (NamingException e) { logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e); return false; } } return false; }