List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY
String INITIAL_CONTEXT_FACTORY
To view the source code for javax.naming Context INITIAL_CONTEXT_FACTORY.
Click Source Link
From source file:jp.ikedam.jenkins.plugins.ldap_sasl.LdapSaslSecurityRealm.java
/** * Authorize a user./*from w ww . j a v a 2 s .c om*/ * * @param username * @param password * @see hudson.security.AbstractPasswordBasedSecurityRealm#authenticate(java.lang.String, java.lang.String) */ @Override protected UserDetails authenticate(String username, String password) throws AuthenticationException { Logger logger = getLogger(); // check configuration. String ldapUris = getValidLdapUris(); if (StringUtils.isBlank(ldapUris)) { logger.severe("No valid LDAP URI is specified."); throw new AuthenticationServiceException("No valid LDAP URI is specified."); } String mechanisms = getMechanisms(); if (StringUtils.isBlank(mechanisms)) { logger.severe("No valid mechanism is specified."); throw new AuthenticationServiceException("No valid mechanism is specified."); } // TODO: Test with LDAPS. // Parameters for JNDI Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUris); env.put(Context.SECURITY_PRINCIPAL, username); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, mechanisms); env.put("com.sun.jndi.ldap.connect.timeout", Integer.toString(getConnectionTimeout())); env.put("com.sun.jndi.ldap.read.timeout", Integer.toString(getReadTimeout())); logger.fine("Authenticating with LDAP-SASL:"); logger.fine(String.format("username=%s", username)); logger.fine(String.format("servers=%s", ldapUris)); logger.fine(String.format("mech=%s", mechanisms)); LdapContext ctx = null; try { ctx = new InitialLdapContext(env, null); } catch (javax.naming.AuthenticationException e) { // Authentication Failure... throw new BadCredentialsException(String.format("Authentication failed: %s", username), e); } catch (NamingException e) { // Unexpected failure... throw new AuthenticationServiceException(String.format("Authentication failed: %s", username), e); } String userDn = (getUserDnResolver() != null) ? getUserDnResolver().getUserDn(ctx, username) : null; logger.fine(String.format("User DN is %s", userDn)); List<GrantedAuthority> authorities = (getGroupResolver() != null) ? getGroupResolver().resolveGroup(ctx, userDn, username) : new ArrayList<GrantedAuthority>(); logger.fine("Authenticating succeeded."); return new LdapUser(username, "", // password(not used) userDn, // dn of this user. true, // enabled true, // accountNonExpired true, // credentialsNonExpired true, // accountNonLocked authorities.toArray(new GrantedAuthority[0])); }
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 * /*w w w. ja v a 2s.com*/ * @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:org.orbeon.oxf.processor.LDAPProcessor.java
private DirContext connect(Config config) { try {// w ww .j ava 2 s .c o 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:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
protected DirContext open() throws NamingException { if (context != null) { return context; }/*from w ww .j ava 2 s. co 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:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Reads JNDI connection information from the configuration. * <br>//from ww w . j a v a 2s. co m * Creates an <code>Hashtable</code> containing the JNDI environment variables. * @param oConfigurationManager The configuration manager * @param eConfig the configuration section * @return <code>DirContext</code> that contains the JNDI connection * @throws AttributeException if configuration reading fails */ private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig) throws AttributeException { Hashtable<String, String> htEnvironment = new Hashtable<String, String>(11); try { Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal"); if (eSecurityPrincipal == null) { _logger.error("No 'security_principal' section found in 'resource' configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn"); if (sPrincipal == null) { _logger.error("No item 'dn' item found in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password"); if (sPassword == null) { _logger.error("No 'password' item found in configuration "); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sDriver = oConfigurationManager.getParam(eConfig, "driver"); if (sDriver == null) { _logger.error("No 'driver' item found in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } String sUrl = oConfigurationManager.getParam(eConfig, "url"); if (sUrl == null) { _logger.error("No valid config item 'url' found in configuration"); throw new AttributeException(SystemErrors.ERROR_CONFIG_READ); } if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) { // Request SSL transport htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); _logger.info("SSL enabled"); } else { _logger.info("SSL disabled"); } htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver); htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple"); htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); htEnvironment.put(Context.PROVIDER_URL, sUrl); } catch (AttributeException e) { throw e; } catch (Exception e) { _logger.error("Could not create a connection", e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } return htEnvironment; }
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();/*from www . j av a 2 s. com*/ 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:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
protected Properties getContextEnvironment() { final Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); props.put(Context.PROVIDER_URL, null == ldapHost ? "" : ldapHost); if (null == credentials || credentials.isEmpty()) { props.put(Context.SECURITY_AUTHENTICATION, LdapConstants.SECURITY_AUTHENTICATION_NONE); } else {/* www. ja v a 2 s. c om*/ props.put(Context.SECURITY_AUTHENTICATION, LdapConstants.SECURITY_AUTHENTICATION_SIMPLE); props.put(Context.SECURITY_PRINCIPAL, null == principal ? "" : principal); props.put(Context.SECURITY_CREDENTIALS, credentials); } // The following properties are specific to com.sun.jndi.ldap.LdapCtxFactory props.put(PROPERTY_NAME_CONNECTION_POOL, Boolean.toString(useConnectionPool)); if (connectionTimeout > -1) { props.put(PROPERTY_NAME_CONNECT_TIMEOUT, Integer.toString(connectionTimeout)); } if (readTimeout > -1) { props.put(PROPERTY_NAME_READ_TIMEOUT, Integer.toString(readTimeout)); } return props; }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Helper method to create the LDAP context needed to interact with the Active Directory. * * @return the relevant LdapContext//from ww w .j a v a 2 s .c o m * @throws KerberosKDCConnectionException if a connection to the KDC cannot be made * @throws KerberosAdminAuthenticationException if the administrator credentials fail to authenticate * @throws KerberosRealmException if the realm does not map to a KDC * @throws KerberosOperationException if an unexpected error occurred */ protected LdapContext createLdapContext() throws KerberosOperationException { KerberosCredential administratorCredentials = getAdministratorCredentials(); Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CONTEXT_FACTORY_CLASS); properties.put(Context.PROVIDER_URL, ldapUrl); properties.put(Context.SECURITY_PRINCIPAL, administratorCredentials.getPrincipal()); properties.put(Context.SECURITY_CREDENTIALS, administratorCredentials.getPassword()); properties.put(Context.SECURITY_AUTHENTICATION, "simple"); properties.put(Context.REFERRAL, "follow"); properties.put("java.naming.ldap.factory.socket", TrustingSSLSocketFactory.class.getName()); try { return createInitialLdapContext(properties, null); } catch (CommunicationException e) { String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl, e.getMessage()); LOG.warn(message, e); throw new KerberosKDCConnectionException(message, e); } catch (AuthenticationException e) { String message = String.format("Failed to authenticate with the Active Directory at %s: %s", ldapUrl, e.getMessage()); LOG.warn(message, e); throw new KerberosAdminAuthenticationException(message, e); } catch (NamingException e) { String error = e.getMessage(); if ((error != null) && !error.isEmpty()) { String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl, e.getMessage()); LOG.warn(message, e); if (error.startsWith("Cannot parse url:")) { throw new KerberosKDCConnectionException(message, e); } else { throw new KerberosOperationException(message, e); } } else { throw new KerberosOperationException("Unexpected error condition", e); } } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Reads JNDI connection information from the configuration. * <br>//from w ww . ja v a2 s.c o m * Creates an <code>Hashtable</code> containing the JNDI environment variables. * @param oConfigurationManager The configuration manager * @param eConfig the configuration section * @return <code>DirContext</code> that contains the JNDI connection * @throws UserException if configuration reading fails */ private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig) throws UserException { Hashtable<String, String> htEnvironment = new Hashtable<String, String>(); try { Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal"); if (eSecurityPrincipal == null) { _logger.error("No 'security_principal' section found in 'resource' configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn"); if (sPrincipal == null) { _logger.error("No item 'dn' item found in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password"); if (sPassword == null) { _logger.error("No 'password' item found in configuration "); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } String sDriver = oConfigurationManager.getParam(eConfig, "driver"); if (sDriver == null) { _logger.error("No 'driver' item found in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } String sUrl = oConfigurationManager.getParam(eConfig, "url"); if (sUrl == null) { _logger.error("No valid config item 'url' found in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) { // Request SSL transport htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); _logger.info("SSL enabled"); } else { _logger.info("SSL disabled"); } htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver); htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple"); htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); htEnvironment.put(Context.PROVIDER_URL, sUrl); } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not create a connection", e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } return htEnvironment; }
From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java
/** * This method retrieves data using LDAP protocol. * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com * - ex URL from AIA ldap://xadessrv.plugtests.net/CN=LevelBCAOK,OU=Plugtests_2015-2016,O=ETSI,C=FR?cACertificate;binary * * @param urlString//from w w w . j a v a 2 s . c o m * @return */ private byte[] ldapGet(final String urlString) { 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, urlString); try { String attributeName = StringUtils.substringAfterLast(urlString, "?"); if (StringUtils.isEmpty(attributeName)) { // default was CRL attributeName = "certificateRevocationList;binary"; } final DirContext ctx = new InitialDirContext(env); final Attributes attributes = ctx.getAttributes(StringUtils.EMPTY); final Attribute attribute = attributes.get(attributeName); final byte[] ldapBytes = (byte[]) attribute.get(); if (ArrayUtils.isEmpty(ldapBytes)) { throw new DSSException("Cannot download CRL from: " + urlString); } return ldapBytes; } catch (Exception e) { LOG.warn(e.getMessage(), e); } return null; }