Example usage for javax.naming Context PROVIDER_URL

List of usage examples for javax.naming Context PROVIDER_URL

Introduction

In this page you can find the example usage for javax.naming Context PROVIDER_URL.

Prototype

String PROVIDER_URL

To view the source code for javax.naming Context PROVIDER_URL.

Click Source Link

Document

Constant that holds the name of the environment property for specifying configuration information for the service provider to use.

Usage

From source file:org.apache.jackrabbit.oak.security.authentication.ldap.AbstractServer.java

/**
 * Sets the contexts of this class taking into account the extras and overrides
 * properties./*from  w  w w.j a v  a2  s  .  c om*/
 *
 * @param env an environment to use while setting up the system root.
 * @throws NamingException if there is a failure of any kind
 */
protected void setContexts(Hashtable<String, Object> env) throws Exception {
    Hashtable<String, Object> envFinal = new Hashtable<String, Object>(env);
    envFinal.put(Context.PROVIDER_URL, "");
    rootDSE = directoryService.getAdminSession();
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.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
 *
 * @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 {

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes("");
        final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary");
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ldapBytes == null || ldapBytes.length == 0) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:ru.efo.security.ADUserDetailsService.java

private DirContext getDirContext(String username, String password) throws NamingException {
    final Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.SECURITY_AUTHENTICATION, "simple");
    props.put(Context.SECURITY_PRINCIPAL, username);
    props.put(Context.SECURITY_CREDENTIALS, password);
    props.put(Context.PROVIDER_URL, ldapUrl);
    props.put("java.naming.ldap.attributes.binary", "objectSID");

    return new InitialDirContext(props);
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

@Test
public void testSaslGssapiLdapAuth() throws Exception {

    final Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");

    LoginContext loginContext = new LoginContext("broker-sasl-gssapi");
    loginContext.login();/* www .  j a  v a2s  .  c o m*/
    try {
        Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> {

            HashSet<String> set = new HashSet<>();

            DirContext ctx = new InitialDirContext(env);
            NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

            while (list.hasMore()) {
                NameClassPair ncp = list.next();
                set.add(ncp.getName());
            }

            Assert.assertTrue(set.contains("uid=first"));
            Assert.assertTrue(set.contains("cn=users"));
            Assert.assertTrue(set.contains("ou=configuration"));
            Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));

            ctx.close();
            return null;

        });
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

protected InitialDirContext buildInitialDirContext(final Map<String, String> config, final int pageSize,
        final AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic
            : new AuthenticationDiagnostic();

    final String securityPrincipal = config.get(Context.SECURITY_PRINCIPAL);
    final String providerURL = config.get(Context.PROVIDER_URL);

    if (this.isSSLSocketFactoryRequired(config)) {
        final KeyStore trustStore = this.initTrustStore();
        ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName());
    }//www  .j av  a2 s.  c om

    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            final InitialLdapContext ctx = new InitialLdapContext(new Hashtable<>(config), null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            final InitialDirContext ret = new InitialDirContext(new Hashtable<>(config));
            final Object[] args = { providerURL, securityPrincipal };
            effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (final javax.naming.AuthenticationException ax) {
        final Object[] args1 = { securityPrincipal };
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);

        // wrong user/password - if we get this far the connection is O.K
        final Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", effectiveDiagnostic, args2, ax);
    } catch (final CommunicationException ce) {
        final Object[] args1 = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);

        final StringBuffer message = new StringBuffer();

        message.append(ce.getClass().getName() + ", " + ce.getMessage());

        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", effectiveDiagnostic, args, ce);
    } catch (final NamingException nx) {
        final Object[] args = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        final StringBuffer message = new StringBuffer();

        message.append(nx.getClass().getName() + ", " + nx.getMessage());

        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", effectiveDiagnostic, args1, nx);
    } catch (final IOException e) {
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Bind authenticate.//  w w w  .j  av  a2  s  . c  om
 *
 * @param username the user to be used
 * @param password the password to be used
 * @return true if the user was authenticated
 * @throws PortalServiceException for any errors encountered
 */
public boolean authenticate(String username, String password) throws PortalServiceException {
    DirContext ctx = null;
    try {
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, env.getProperty(Context.INITIAL_CONTEXT_FACTORY));
        props.put(Context.PROVIDER_URL, env.getProperty(Context.PROVIDER_URL));
        props.put(Context.SECURITY_PRINCIPAL, MessageFormat.format(userDNPattern, username));
        props.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialDirContext(props);
        return true;
    } catch (AuthenticationException authEx) {
        return false;
    } catch (NamingException e) {
        throw new PortalServiceException("Could not verify authentication results.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.LdapSaslSecurityRealm.java

/**
 * Authorize a user.//from w ww  .  j a va 2  s. c o m
 * 
 * @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
 * //  ww w .j  a  v  a 2 s .  c o  m
 * @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 {/*from ww w . j a  v 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:org.hyperic.hq.plugin.jboss.JBossDetector.java

public List<ServerResource> getServerList(String installpath, long pid) throws PluginException {
    File configDir = new File(installpath);
    getLog().debug("[getServerList] configDir='" + configDir + "'");
    File serviceXML = new File(configDir, JBOSS_SERVICE_XML);
    File distDir = configDir.getParentFile().getParentFile();

    // jboss copies the config set into the tmp deploy dir
    if (distDir.getName().equals("deploy")) {
        return null;
    }//w w  w .  j a va  2  s . c o  m

    String serverName = configDir.getName();

    String fullVersion = getVersion(configDir, "jboss-j2ee.jar");

    // 5.0
    if (fullVersion == null) {
        fullVersion = getVersion(configDir.getParentFile().getParentFile(), "jboss-j2se.jar");
    }
    if (fullVersion == null) {
        getLog().debug("unable to determine JBoss version in: " + configDir);
        return null;
    }

    String typeVersion = fullVersion.substring(0, 3);

    if (!getTypeInfo().getVersion().equals(typeVersion)) {
        getLog().debug(configDir + " (" + fullVersion + ")" + " is not a " + getName());
        return null;
    }

    getLog().debug("discovered JBoss server [" + serverName + "] in " + configDir);

    ConfigResponse _config = new ConfigResponse();
    ConfigResponse controlConfig = new ConfigResponse();
    ConfigResponse metricConfig = new ConfigResponse();

    JBossConfig cfg = JBossConfig.getConfig(serviceXML);

    String address = getBindAddress(cfg, installpath);

    String jnpUrl = "jnp://" + address + ":" + cfg.getJnpPort();
    getLog().debug("JNP url=" + jnpUrl);

    _config.setValue(Context.PROVIDER_URL, jnpUrl);

    //for use w/ -jar hq-pdk.jar or agent.properties
    Properties props = getManager().getProperties();
    String[] credProps = { Context.PROVIDER_URL, Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS };
    for (int i = 0; i < credProps.length; i++) {
        String value = props.getProperty(credProps[i]);
        if (value != null) {
            _config.setValue(credProps[i], value);
        }
    }

    String script = distDir + File.separator + JBossServerControlPlugin.getControlScript(isWin32());

    controlConfig.setValue(ServerControlPlugin.PROP_PROGRAM, getCanonicalPath(script));

    controlConfig.setValue(JBossServerControlPlugin.PROP_CONFIGSET, serverName);

    String logDir = ".." + File.separator + ".." + File.separator + ".." + File.separator + "logs";
    File brandedLogDir = new File(installpath, logDir);

    if (!brandedLogDir.exists()) {
        logDir = "log";
    }

    metricConfig.setValue(Log4JLogTrackPlugin.PROP_FILES_SERVER, logDir + File.separator + "server.log");

    ServerResource server = createServerResource(installpath);

    server.setConnectProperties(new String[] { Context.PROVIDER_URL });
    if (pid > 0) {
        populateListeningPorts(pid, _config, true);
    }

    server.setProductConfig(_config);
    server.setMeasurementConfig(metricConfig);
    server.setControlConfig(controlConfig);

    if (JBossProductPlugin.isBrandedServer(configDir, getPluginProperty("brand.ear"))) {
        // Branded JBoss
        String brandName = getPluginProperty("brand.name");
        server.setName(getPlatformName() + " " + brandName);
        server.setIdentifier(brandName);
    } else {
        server.setName(server.getName() + " " + serverName);
    }

    File home = cfg.getJBossHome();
    if (home != null) {
        //normally setup in JBossProductPlugin
        //this handles the case of the agent being started
        //before the JBoss server
        adjustClassPath(home.getPath());
    }
    //pickup any jars found relative to this installpath
    adjustClassPath(installpath);

    List<ServerResource> servers = new ArrayList<ServerResource>();
    //apply externally defined AUTOINVENTORY_NAME, etc.
    if (pid > 0) {
        discoverServerConfig(server, pid);
    }
    servers.add(server);

    return servers;
}