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.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected DirContext open() throws NamingException {
    if (context != null) {
        return context;
    }/*  ww  w  .j  av  a 2 s.c om*/
    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.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 va 2 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: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 {//from   w  w  w.j  av 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  w w  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.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>//w w  w . j  a  va  2s .com
 * 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: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   ww w .ja v a 2s. co 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;
}

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 ww .  j  av a 2s  .  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:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>/*www . j  ava2 s.c  om*/
 * 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:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void createSampleEntity() throws Exception {

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    Attributes entry = new BasicAttributes();
    Attribute obClassAttr = new BasicAttribute("objectClass");
    obClassAttr.add("inetOrgPerson");
    entry.put(obClassAttr);//from  ww w . j  a  va 2s  .c o m

    Attribute mailAttr = new BasicAttribute("mail");
    mailAttr.add(testUserId + "@wso2.com");
    entry.put(mailAttr);

    Attribute passAttr = new BasicAttribute("userPassword");
    passAttr.add("12345");
    entry.put(passAttr);

    Attribute snAttr = new BasicAttribute("sn");
    snAttr.add("dim");
    entry.put(snAttr);

    Attribute cnAttr = new BasicAttribute("cn");
    cnAttr.add("dim");
    entry.put(cnAttr);

    String dn = "uid=" + testUserId + "," + userBase;

    ctx.createSubcontext(dn, entry);
}

From source file:org.apache.openaz.xacml.admin.view.components.LDAPPIPConfigurationComponent.java

protected void testLDAPConnection() {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, this.textFieldFactory.getValue());
    env.put(Context.PROVIDER_URL, this.textFieldProviderURL.getValue());
    env.put(Context.SECURITY_PRINCIPAL, this.textFieldPrincipal.getValue());
    env.put(Context.SECURITY_CREDENTIALS, this.textFieldCredentials.getValue());

    String auth = this.comboBoxAuthentication.getValue().toString();
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    ////from   w w  w.  j  a  va  2 s.c o m
    // Do we need to do anything?
    //
    /*
    if (auth.equals(LDAP_AUTH_ANONYMOUS)) {
               
    } else if (auth.equals(LDAP_AUTH_SIMPLE)) {
               
    } else if (auth.equals(LDAP_AUTH_SASL)) {
               
    }
    */

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                .show(Page.getCurrent());
    } catch (NamingException e) {
        logger.error(e);
        new Notification("Connection Failed", "<br/>" + e.getLocalizedMessage(), Type.ERROR_MESSAGE, true)
                .show(Page.getCurrent());
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException idontcare) { //NOPMD
        }
    }
}