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

/**
 * Common code to get an initial context via a simple bind to the
 * server over the wire using the SUN JNDI LDAP provider. Do not use
 * this method until after the setUp() method is called to start the
 * server otherwise it will fail.// w ww  . java2s .  c  o  m
 *
 * @param bindPrincipalDn the DN of the principal to bind as
 * @param password        the password of the bind principal
 * @return an LDAP context as the the administrator to the rootDSE
 * @throws NamingException if the server cannot be contacted
 */
protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
    env.put(Context.PROVIDER_URL, "ldap://localhost:" + port);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    return new InitialLdapContext(env, null);
}

From source file:com.evolveum.midpoint.pwdfilter.opendj.PasswordPusher.java

private void readConfig() throws InitializationException {

    String configFile = "/opt/midpoint/opendj-pwdpusher.xml";
    if (System.getProperty("config") != null) {
        configFile = System.getProperty("config");
    }/*from ww w  .  jav a 2 s.c o  m*/

    File f = new File(configFile);
    if (!f.exists() || !f.canRead()) {
        throw new IllegalArgumentException("Config file " + configFile + " does not exist or is not readable");
    }

    try {
        XMLConfiguration config = new XMLConfiguration(f);

        String notifierDN = "cn=" + config.getString("passwordpusher.statusNotifierName")
                + ",cn=Account Status Notification Handlers";
        String ldapURL = config.getString("passwordpusher.ldapServerURL");
        boolean ldapSSL = config.getBoolean("passwordpusher.ldapServerSSL");
        String ldapUsername = config.getString("passwordpusher.ldapServerUsername");
        String ldapPassword = config.getString("passwordpusher.ldapServerPassword");

        Hashtable<Object, Object> env = new Hashtable<Object, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapURL + "/cn=config");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
        env.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        if (ldapSSL) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
        }

        try {
            DirContext context = new InitialDirContext(env);
            Attributes attr = context.getAttributes(notifierDN);

            this.endPoint = attr.get("ds-cfg-referrals-url").get(0).toString();
            this.username = attr.get("ds-cfg-midpoint-username").get(0).toString();
            this.password = attr.get("ds-cfg-midpoint-password").get(0).toString();
            this.pwdChangeDirectory = attr.get("ds-cfg-midpoint-passwordcachedir").get(0).toString();
        } catch (NamingException ne) {
            throw new InitializationException(
                    ERR_MIDPOINT_PWDSYNC_READING_CONFIG_FROM_LDAP.get(ne.getMessage()), ne);
        }
    } catch (ConfigurationException ce) {
        throw new InitializationException(ERR_MIDPOINT_PWDSYNC_PARSING_XML_CONFIG.get(ce.getMessage()), ce);
    }
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method for getting the LDAP COntext based on the host,username, password
 * @param host/*from w  w w .  j  a  v  a 2s. com*/
 * @param adminName
 * @param adminPassword
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static LdapContext getLDAPContext(String host, String adminName, String adminPassword)
        throws NamingException {
    //Logger.info("Creating LDAP Context", LDAPUtils.class);
    Hashtable props = System.getProperties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTHENTICATION);
    props.put(Context.SECURITY_PRINCIPAL, adminName);
    props.put(Context.SECURITY_CREDENTIALS, adminPassword);
    props.put(Context.PROVIDER_URL, host);
    if (!StringUtils.isNull(LDAPConfigUtils.getTrustStorePath())) {
        System.setProperty("javax.net.ssl.trustStore", LDAPConfigUtils.getTrustStorePath());
        props.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    //Logger.info("Completed creating LDAP Context for host ["+host+"]", LDAPUtils.class);
    return (new InitialLdapContext(props, null));
}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

private InitialDirContext buildInitialDirContext(Hashtable<String, String> env, int pageSize,
        AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    String securityPrincipal = env.get(Context.SECURITY_PRINCIPAL);
    String providerURL = env.get(Context.PROVIDER_URL);

    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }//from  w w w. ja v a  2s  .c o  m

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

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

        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
        Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", diagnostic, args, cause);
    } catch (NamingException nx) {
        Object[] args = { providerURL };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        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
        Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", diagnostic, args1, nx);
    } catch (IOException e) {
        Object[] args = { providerURL, securityPrincipal };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

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

From source file:org.rhq.enterprise.server.core.CustomJaasDeploymentService.java

private Map<String, String> getLdapOptions(Properties conf) {
    Map<String, String> configOptions = new HashMap<String, String>();

    configOptions.put(Context.INITIAL_CONTEXT_FACTORY, conf.getProperty(RHQConstants.LDAPFactory));
    configOptions.put(Context.PROVIDER_URL, conf.getProperty(RHQConstants.LDAPUrl));
    String value = conf.getProperty(SystemSetting.USE_SSL_FOR_LDAP.getInternalName());
    boolean ldapSsl = "ssl".equalsIgnoreCase(value);
    configOptions.put(Context.SECURITY_PROTOCOL, (ldapSsl) ? "ssl" : null);
    configOptions.put("LoginProperty", conf.getProperty(RHQConstants.LDAPLoginProperty));
    configOptions.put("Filter", conf.getProperty(RHQConstants.LDAPFilter));
    configOptions.put("GroupFilter", conf.getProperty(RHQConstants.LDAPGroupFilter));
    configOptions.put("GroupMemberFilter", conf.getProperty(RHQConstants.LDAPGroupMember));
    configOptions.put("BaseDN", conf.getProperty(RHQConstants.LDAPBaseDN));
    configOptions.put("BindDN", conf.getProperty(RHQConstants.LDAPBindDN));
    configOptions.put("BindPW", conf.getProperty(RHQConstants.LDAPBindPW));

    return configOptions;
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
 * in general when going through the wire protocol.
 *
 * @throws Exception if anything goes wrong
 *///from  w  w  w.j  av  a  2s . c om
@Test
public void testEnableAnonymousBindsOnRootDse() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("", "(objectClass=*)", cons);

    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertEquals("", result.getName().trim());
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private Properties getEnvironment(@Nullable String principal, @Nullable String credentials, boolean pooling) {
    Properties env = new Properties();
    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (realm != null) {
        env.put(SASL_REALM_PROPERTY, realm);
    }//from  ww  w.j a  va 2 s  .c  o m
    if (pooling) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.REFERRAL, DEFAULT_REFERRAL);
    if (principal != null) {
        env.put(Context.SECURITY_PRINCIPAL, principal);
    }
    // Note: debug is intentionally was placed here - in order to not expose password in log
    LOG.debug("Initializing LDAP context {}", env);
    if (credentials != null) {
        env.put(Context.SECURITY_CREDENTIALS, credentials);
    }
    return env;
}

From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

private DirContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());

    try {/*  w  ww. j  a  v  a  2s. c om*/
        return contextFactory.createContext(env);
    } catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials(e);
        } else {
            throw LdapUtils.convertLdapException(e);
        }
    }
}

From source file:py.una.pol.karaku.security.KarakuUserService.java

private InitialDirContext getInitialDirContext(String user, String pass) throws NamingException {

    Map<Object, String> env = new HashMap<Object, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getServerLocation());

    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, pass);
    return new InitialDirContext(new Hashtable<Object, String>(env));
}

From source file:it.openutils.mgnlaws.magnolia.init.ClasspathProviderImpl.java

/**
 * @see info.magnolia.repository.Provider#init(info.magnolia.repository.RepositoryMapping)
 *//*from  w  w  w. j a va 2s. c o  m*/
public void init(RepositoryMapping repositoryMapping) throws RepositoryNotInitializedException {
    checkXmlSettings();

    this.repositoryMapping = repositoryMapping;
    /* connect to repository */
    Map params = this.repositoryMapping.getParameters();
    String configFile = (String) params.get(CONFIG_FILENAME_KEY);
    if (!StringUtils.startsWith(configFile, ClasspathPropertiesInitializer.CLASSPATH_PREFIX)) {
        configFile = Path.getAbsoluteFileSystemPath(configFile);
    }
    String repositoryHome = (String) params.get(REPOSITORY_HOME_KEY);
    repositoryHome = getRepositoryHome(repositoryHome);

    // cleanup the path, to remove eventual ../.. and make it absolute
    try {
        File repoHomeFile = new File(repositoryHome);
        repositoryHome = repoHomeFile.getCanonicalPath();
    } catch (IOException e1) {
        // should never happen and it's not a problem at this point, just pass it to jackrabbit and see
    }

    String clusterid = SystemProperty.getProperty(MAGNOLIA_CLUSTERID_PROPERTY);
    if (StringUtils.isNotBlank(clusterid)) {
        System.setProperty(JACKRABBIT_CLUSTER_ID_PROPERTY, clusterid);
    }

    // get it back from system properties, if it has been set elsewhere
    clusterid = System.getProperty(JACKRABBIT_CLUSTER_ID_PROPERTY);

    log.info("Loading repository at {} (config file: {}) - cluster id: \"{}\"",
            new Object[] { repositoryHome, configFile, StringUtils.defaultString(clusterid, "<unset>") });

    bindName = (String) params.get(BIND_NAME_KEY);
    jndiEnv = new Hashtable<String, Object>();
    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, params.get(CONTEXT_FACTORY_CLASS_KEY));
    jndiEnv.put(Context.PROVIDER_URL, params.get(PROVIDER_URL_KEY));

    try {
        InitialContext ctx = new InitialContext(jndiEnv);
        // first try to find the existing object if any
        try {
            this.repository = (Repository) ctx.lookup(bindName);
        } catch (NameNotFoundException ne) {
            log.debug("No JNDI bound Repository found with name {}, trying to initialize a new Repository",
                    bindName);
            ClasspathRegistryHelper.registerRepository(ctx, bindName, configFile, repositoryHome, true);
            this.repository = (Repository) ctx.lookup(bindName);
        }
        this.validateWorkspaces();
    } catch (NamingException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (RepositoryException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    }
}