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.hadoop.security.LdapGroupsMapping.java

DirContext getDirContext() throws NamingException {
    if (ctx == null) {
        // Set up the initial environment for LDAP connectivity
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.ldap.LdapCtxFactory.class.getName());
        env.put(Context.PROVIDER_URL, ldapUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        // Set up SSL security, if necessary
        if (useSsl) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
            System.setProperty("javax.net.ssl.keyStore", keystore);
            System.setProperty("javax.net.ssl.keyStorePassword", keystorePass);
        }/*ww  w. java 2s.  c  om*/

        env.put(Context.SECURITY_PRINCIPAL, bindUser);
        env.put(Context.SECURITY_CREDENTIALS, bindPassword);

        env.put("com.sun.jndi.ldap.connect.timeout",
                conf.get(CONNECTION_TIMEOUT, String.valueOf(CONNECTION_TIMEOUT_DEFAULT)));
        env.put("com.sun.jndi.ldap.read.timeout", conf.get(READ_TIMEOUT, String.valueOf(READ_TIMEOUT_DEFAULT)));

        ctx = new InitialDirContext(env);
    }

    return ctx;
}

From source file:org.lsc.jndi.JndiServices.java

private void logConnectingTo(Properties connProps) {
    if (LOGGER.isInfoEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Connecting to LDAP server ");
        sb.append(connProps.getProperty(Context.PROVIDER_URL));

        // log identity used to connect
        if (connProps.getProperty(Context.SECURITY_AUTHENTICATION) == null
                || connProps.getProperty(Context.SECURITY_AUTHENTICATION).equals("none")) {
            sb.append(" anonymously");
        } else {/*from  w ww .  j  a  v a 2 s. c  o  m*/
            sb.append(" as ");
            sb.append(connProps.getProperty(Context.SECURITY_PRINCIPAL));
        }

        // using TLS ?
        if (connProps.get(TLS_CONFIGURATION) != null && (Boolean) connProps.get(TLS_CONFIGURATION)) {
            sb.append(" with STARTTLS extended operation");
        }

        LOGGER.info(sb.toString());
    }
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind)
        throws AuthenticationException, NamingException {

    env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);

    DirContext ctx = null;/* w  ww .j a v  a  2  s . c o  m*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException ne) {
        log.error("Failed to bind as: {}", ldapSecurityPrincipal);
    }

    // ensure we have the userPassword attribute at a minimum
    String[] attributeList = new String[] { "userPassword" };

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(attributeList);
    sc.setDerefLinkFlag(true);
    sc.setReturningObjFlag(false);
    sc.setTimeLimit(5000);

    String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")";
    // Do the search
    NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc);
    if (!results.hasMore()) {
        log.warn("no valid user found.");
        return false;
    }

    SearchResult result = results.next();
    log.debug("authenticating user: {}", result.getNameInNamespace());

    if (bind) {
        // setup user context for binding
        Hashtable<String, String> userEnv = new Hashtable<String, String>();
        userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        userEnv.put(Context.PROVIDER_URL, baseUrl);
        userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace());
        userEnv.put(Context.SECURITY_CREDENTIALS, password);

        try {
            new InitialDirContext(userEnv);
        } catch (NamingException ne) {
            log.error("failed to authenticate user: " + result.getNameInNamespace());
            throw ne;
        }
    } else {
        // get userPassword attribute
        Attribute up = result.getAttributes().get("userPassword");
        if (up == null) {
            log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace());
            return false;
        }

        byte[] userPasswordBytes = (byte[]) up.get();
        String userPassword = new String(userPasswordBytes);

        // compare passwords - also handles encodings
        if (!passwordsMatch(password, userPassword)) {
            return false;
        }
    }

    return true;
}

From source file:org.springframework.ldap.core.support.AbstractContextSource.java

private Hashtable setupAnonymousEnv() {
    if (pooled) {
        baseEnv.put(SUN_LDAP_POOLING_FLAG, "true");
        log.debug("Using LDAP pooling.");
    } else {//from  ww  w.j a  v a2s  . co m
        baseEnv.remove(SUN_LDAP_POOLING_FLAG);
        log.debug("Not using LDAP pooling");
    }

    Hashtable env = new Hashtable(baseEnv);

    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory.getName());
    env.put(Context.PROVIDER_URL, assembleProviderUrlString(urls));

    if (dirObjectFactory != null) {
        env.put(Context.OBJECT_FACTORIES, dirObjectFactory.getName());
    }

    if (!StringUtils.isBlank(referral)) {
        env.put(Context.REFERRAL, referral);
    }

    if (!DistinguishedName.EMPTY_PATH.equals(base)) {
        // Save the base path for use in the DefaultDirObjectFactory.
        env.put(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY, base);
    }

    log.debug("Trying provider Urls: " + assembleProviderUrlString(urls));

    return env;
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>//from w  w  w.  java  2s . 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 OAException if configuration reading fails
 */
private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig)
        throws OAException {
    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 OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn");
        if (sPrincipal == null) {
            _logger.error("No item 'dn' item found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password");
        if (sPassword == null) {
            _logger.error("No 'password' item found in configuration ");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDriver = oConfigurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.error("No 'driver' item found in configuration");
            throw new OAException(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 OAException(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 (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create a connection", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
    return htEnvironment;
}

From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java

private DirContext createContext() throws NamingException {
    // Create a environment container
    Hashtable<Object, Object> env = new Hashtable<>();

    String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort();

    // Create a new context pointing to the partition
    env.put(Context.PROVIDER_URL, 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, "com.sun.jndi.ldap.LdapCtxFactory");

    // Let's open a connection on this partition
    InitialContext initialContext = new InitialContext(env);

    // We should be able to read it
    DirContext appRoot = (DirContext) initialContext.lookup("");
    Assert.assertNotNull(appRoot);//from   w  ww . ja  v a 2 s  .  c om

    return appRoot;
}

From source file:com.communote.server.test.ldap.AbstractApacheDSServer.java

/**
 * Sets the contexts of this class taking into account the extras and overrides properties.
 *
 * @param env/*ww  w.ja v  a  2  s  .  co  m*/
 *            an environment to use while setting up the system root.
 * @throws Exception
 *             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, ServerDNConstants.SYSTEM_DN);
    setSysRoot(new InitialLdapContext(envFinal, null));

    envFinal.put(Context.PROVIDER_URL, "");
    setRootDSE(getDirectoryService().getAdminSession());

    envFinal.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    setSchemaRoot(new InitialLdapContext(envFinal, null));
}

From source file:it.doqui.index.ecmengine.client.engine.EcmEngineDirectDelegateImpl.java

protected EcmEngineMassiveBusinessInterface createMassiveService() throws Throwable {
    this.log.debug("[" + getClass().getSimpleName() + "::createMassiveService] BEGIN ");

    Properties properties = new Properties();

    // Caricamento del file contenenti le properties su cui fare il binding
    rb = ResourceBundle.getBundle(ECMENGINE_PROPERTIES_FILE);

    // Caricamento delle proprieta' su cui fare il binding all'oggetto di business delle funzionalita'
    // implementate per la ricerca.
    try {/*from w  w  w.jav  a2 s.  co m*/
        this.log.debug("[" + getClass().getSimpleName() + "::createMassiveService] P-Delegata di massive.");

        this.log.debug("[" + getClass().getSimpleName() + "::createMassiveService] context factory vale : "
                + rb.getString(ECMENGINE_CONTEXT_FACTORY));
        properties.put(Context.INITIAL_CONTEXT_FACTORY, rb.getString(ECMENGINE_CONTEXT_FACTORY));
        this.log.debug("[" + getClass().getSimpleName() + "::createMassiveService] url to connect vale : "
                + rb.getString(ECMENGINE_URL_TO_CONNECT));
        properties.put(Context.PROVIDER_URL, rb.getString(ECMENGINE_URL_TO_CONNECT));

        // Controllo che la property cluster partition sia valorizzata per capire se
        // sto lavorando in una configurazione in cluster oppure no
        String clusterPartition = rb.getString(ECMENGINE_CLUSTER_PARTITION);
        this.log.debug("[" + getClass().getSimpleName() + "::createMassiveService] clusterPartition vale : "
                + clusterPartition);
        if (clusterPartition != null && clusterPartition.length() > 0) {
            properties.put("jnp.partitionName", clusterPartition);
            this.log.debug(
                    "[" + getClass().getSimpleName() + "::createMassiveService] disable discovery vale : "
                            + rb.getString(ECMENGINE_DISABLE_DISCOVERY));
            properties.put("jnp.disableDiscovery", rb.getString(ECMENGINE_DISABLE_DISCOVERY));
        }

        // Get an initial context
        InitialContext jndiContext = new InitialContext(properties);
        log.debug("[" + getClass().getSimpleName() + "::createMassiveService] context istanziato");

        // Get a reference to the Bean
        Object ref = jndiContext.lookup(ECMENGINE_MASSIVE_JNDI_NAME);

        // Get a reference from this to the Bean's Home interface
        EcmEngineMassiveHome home = (EcmEngineMassiveHome) PortableRemoteObject.narrow(ref,
                EcmEngineMassiveHome.class);

        // Create an Adder object from the Home interface
        return home.create();

    } catch (Throwable e) {
        this.log.error("[" + getClass().getSimpleName() + "::createMassiveService] "
                + "Impossibile l'EJB di security: " + e.getMessage());
        throw e;
    } finally {
        this.log.debug("[" + getClass().getSimpleName() + "::createMassiveService] END ");
    }
}

From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java

private boolean checkUsernamePassword(String username, String password, String authorizePathMode) {
    String dnUser = Misc.replace(ldapAuthUserBase, "%UID%", username);

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapAuthUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, dnUser);
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = null;/*from   ww w .  ja va2  s . c om*/
    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);
        }

        if (authorizePathMode == null) {
            return true;
        } else {
            if (authorizePathMode.equals(AUTH_PATH_MODE_OBSERVER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthObserverBase)) {
                    return true;
                }
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_DATAADMIN)) {
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_TESTER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthTesterBase)) {
                    return true;
                }
            }
        }
    } catch (AuthenticationException e) {
        return false;
    } catch (Exception e) {
        log.warn("LoginFilter caught Exception", e);
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                log.warn("LoginFilter caught Exception", e);
            }
        }
    }
    return false;
}

From source file:org.settings4j.connector.JNDIConnectorTest.java

private void removeJNDIContextProperties() {
    System.getProperties().remove(Context.INITIAL_CONTEXT_FACTORY);
    System.getProperties().remove(Context.PROVIDER_URL);
    System.getProperties().remove(Context.URL_PKG_PREFIXES);
}