Example usage for javax.naming Context SECURITY_PRINCIPAL

List of usage examples for javax.naming Context SECURITY_PRINCIPAL

Introduction

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

Prototype

String SECURITY_PRINCIPAL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the identity of the principal for authenticating the caller to the service.

Usage

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

public InitialDirContext getInitialDirContext(String principal, String credentials,
        AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    if (diagnostic == null) {
        diagnostic = new AuthenticationDiagnostic();
    }/* ww w  .  j a v a 2  s  . c om*/

    if (principal == null) {
        // failed before we tried to do anything
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Null user name provided.", diagnostic);
    }

    if (principal.length() == 0) {
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Empty user name provided.", diagnostic);
    }

    if (credentials == null) {
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("No credentials provided.", diagnostic);
    }

    if (credentials.length() == 0) {
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Empty credentials provided.", diagnostic);
    }

    diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, true, null);

    Hashtable<String, String> env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.put(Context.SECURITY_PRINCIPAL, principal);
    env.put(Context.SECURITY_CREDENTIALS, credentials);

    return buildInitialDirContext(env, 0, diagnostic);
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Authenticates the user using the supplied credentials and retrieves the
 * requested attributes.//from w w w  .jav a  2  s  .  co m
 * @param userCredentials
 *            User's credentials. Cannot be <code>null</code>.
 * @param attributeRequest
 *            Requested attributes.
 * @return The requested attributes (<code>String</code> names and
 *         <code>String[]</code> values), if they did exist in the
 *         external backend. Otherwise returns those attributes that could
 *         actually be read, this may be an empty <code>HashMap</code>.
 *         Returns an empty <code>HashMap</code> if
 *         <code>attributeRequest</code> is <code>null</code> or an
 *         empty array.
 * @throws AuthenticationFailedException
 *             If the authentication fails.
 * @throws BackendException
 *             If there is a problem accessing the backend.
 * @throws IllegalArgumentException
 *             If <code>userCredentials</code> is <code>null</code>.
 */
public final HashMap<String, String[]> authenticate(final Credentials userCredentials,
        final String[] attributeRequest) throws AuthenticationFailedException, BackendException {

    // Sanity check.
    if (userCredentials == null)
        throw new IllegalArgumentException("Credentials cannot be NULL");

    // Go through all references.
    for (int i = 0; i < myReferences.length; i++) {
        final String[] references = myReferences[i].getReferences();
        final String[] usernames = myReferences[i].getUsernames();
        final String[] passwords = myReferences[i].getPasswords();
        for (int j = 0; j < references.length; j++) {

            // For the benefit of the finally block below.
            InitialLdapContext ldap = null;

            try {

                // Context for this reference.
                try {
                    ldap = connect(references[j]);
                } catch (NamingException e) {
                    // Connection failed, but we might have other sources.
                    log.logWarn("Unable to access the backend on '" + references[j] + "': "
                            + e.getClass().getName(), mySessionTicket, e);
                    continue;
                }

                // Skip search phase if the reference(s) are explicit.
                String rdn = "";
                if (myReferences[i].isExplicitlyIndexed()) {

                    // Add the explicit reference; no search phase, no RDN.
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL,
                            references[j].substring(references[j].lastIndexOf('/') + 1));

                } else {

                    // Anonymous search or not?
                    ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                    if ((usernames[j].length() == 0) && (passwords[j].length() > 0))
                        log.logWarn(
                                "Search username is empty but search password is not - possible index problem",
                                mySessionTicket);
                    else if ((passwords[j].length() == 0) && (usernames[j].length() > 0))
                        log.logWarn(
                                "Search password is empty but search username is not - possible index problem",
                                mySessionTicket);
                    else if ((passwords[j].length() == 0) && (usernames[j].length() == 0)) {
                        log.logDebug("Anonymous search for user element DN on " + references[j],
                                mySessionTicket);
                        ldap.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
                    } else
                        log.logDebug("Non-anonymous search for user element DN on " + references[j],
                                mySessionTicket);
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, usernames[j]);
                    ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, passwords[j]);

                    // Search using the implicit reference.
                    String pattern = usernameAttribute + '=' + userCredentials.getUsername();
                    rdn = ldapSearch(ldap, pattern);
                    if (rdn == null) {

                        // No user element found. Try to guess the RDN.
                        rdn = userCredentials.getUsername();
                        rdn = guessedAttribute + '=' + rdn.substring(0, rdn.indexOf('@'));
                        log.logDebug("No subtree match for " + pattern + " on " + references[j]
                                + " - guessing on RDN " + rdn, mySessionTicket);

                    } else
                        log.logDebug("Matched " + pattern + " to " + rdn + ',' + ldap.getNameInNamespace(),
                                mySessionTicket);
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, rdn + ',' + ldap.getNameInNamespace());
                }

                // Authenticate and get attributes.
                ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, userCredentials.getPassword());
                try {
                    ldap.reconnect(null);
                    log.logDebug("Successfully authenticated " + userCredentials.getUsername() + " on "
                            + references[j], mySessionTicket);
                    return getAttributes(ldap, rdn, attributeRequest); // Success.
                } catch (AuthenticationException e) {

                    // Authentication failed, but we may have other
                    // references.
                    log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on "
                            + references[j] + " - authentication failed", mySessionTicket);
                    continue;

                } catch (AuthenticationNotSupportedException e) {

                    // Password authentication not supported for the DN.
                    // We may still have other references.
                    log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on "
                            + references[j] + " - authentication not supported", mySessionTicket);
                    continue;

                }

            } catch (ConfigurationException e) {
                throw new BackendException("Backend configuration problem with " + references[j], e);
            } catch (NamingException e) {
                throw new BackendException("Unable to access the backend on " + references[j], e);
            } finally {

                // Close the LDAP connection.
                if (ldap != null) {
                    try {
                        ldap.close();
                    } catch (NamingException e) {
                        // Ignored.
                        log.logWarn(
                                "Unable to close the backend connection to " + references[j] + " - ignoring",
                                mySessionTicket, e);
                    }
                }
            }

        }
    }

    // No user was found.
    throw new AuthenticationFailedException(
            "Failed to authenticate user " + userCredentials.getUsername() + " - no user found");

}

From source file:org.apache.syncope.core.rest.AbstractTest.java

@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" })
protected Object getLdapRemoteObject(final String bindDn, final String bindPwd, final String objectDn) {
    ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP);
    final Map<String, ConnConfProperty> ldapConnConf = connectorService.read(ldapRes.getConnectorId())
            .getConfigurationMap();/*  w w  w .  j  av a2 s.co m*/

    Hashtable env = new Hashtable();
    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);

    try {
        final InitialDirContext ctx = new InitialDirContext(env);
        return ctx.lookup(objectDn);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.mirth.connect.connectors.jms.JmsDispatcher.java

/**
 * Get the JmsConnection from the cache if one exists, otherwise a new one will be created. This
 * method is synchronized otherwise multiple threads may try to create the same connection
 * simultaneously. Only one thread is allowed to create a connection at a time. Subsequent
 * threads will then retrieve the connection that was already created.
 *///w ww  .ja  v  a2  s  . co  m
private synchronized JmsConnection getJmsConnection(JmsDispatcherProperties jmsDispatcherProperties,
        String connectionKey, Long dispatcherId, boolean replace) throws Exception {
    // If the connection needs to be replaced, clean up the old connection and remove it from the cache.
    if (replace) {
        closeJmsConnectionQuietly(connectionKey);
    }

    JmsConnection jmsConnection = jmsConnections.get(connectionKey);

    if (jmsConnection == null) {
        if (jmsConnections.size() >= maxConnections) {
            throw new Exception("Cannot create new connection. Maximum number (" + maxConnections
                    + ") of cached connections reached.");
        }

        Context initialContext = null;
        ConnectionFactory connectionFactory = null;
        Connection connection = null;

        Map<String, String> connectionProperties = jmsDispatcherProperties.getConnectionProperties();
        if (jmsDispatcherProperties.isUseJndi()) {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

            try {
                MirthContextFactory contextFactory = contextFactoryController
                        .getContextFactory(getResourceIds());
                Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

                Hashtable<String, Object> env = new Hashtable<String, Object>();
                env.put(Context.PROVIDER_URL, jmsDispatcherProperties.getJndiProviderUrl());
                env.put(Context.INITIAL_CONTEXT_FACTORY,
                        jmsDispatcherProperties.getJndiInitialContextFactory());
                env.put(Context.SECURITY_PRINCIPAL, jmsDispatcherProperties.getUsername());
                env.put(Context.SECURITY_CREDENTIALS, jmsDispatcherProperties.getPassword());

                initialContext = new InitialContext(env);

                String connectionFactoryName = jmsDispatcherProperties.getJndiConnectionFactoryName();
                connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName);
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
        } else {
            String className = jmsDispatcherProperties.getConnectionFactoryClass();

            MirthContextFactory contextFactory = contextFactoryController.getContextFactory(getResourceIds());
            connectionFactory = (ConnectionFactory) Class
                    .forName(className, true, contextFactory.getApplicationClassLoader()).newInstance();
        }

        BeanUtil.setProperties(connectionFactory, connectionProperties);

        try {
            logger.debug("Creating JMS connection and session");
            connection = connectionFactory.createConnection(jmsDispatcherProperties.getUsername(),
                    jmsDispatcherProperties.getPassword());
            String clientId = jmsDispatcherProperties.getClientId();

            if (!clientId.isEmpty()) {
                connection.setClientID(clientId);
            }

            logger.debug("Starting JMS connection");
            connection.start();
        } catch (JMSException e) {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close JMS connection.", e);
            }

            try {
                if (initialContext != null) {
                    initialContext.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close initial context.", e);
            }

            throw e;
        }

        // Create the new JmsConnection and add it to the cache.
        jmsConnection = new JmsConnection(connection, initialContext);
        jmsConnections.put(connectionKey, jmsConnection);
    }

    return jmsConnection;
}

From source file:com.headstrong.fusion.messaging.model.endpoint.binding.JmsBindingEndPointModeler.java

/**
 * Creates a {@link JmsComponent} using the parameters set.
 * /*from w  w w.ja  v a2s. c o  m*/
 * @param routeBuilder
 * @return {@link JmsComponent}
 * @throws ProcessModellingException
 */
@SuppressWarnings("unchecked")
private Component getJmsComponent(RouteBuilder routeBuilder) throws ProcessModellingException {
    JmsComponent jmsComponent = null;
    if (this.getProvider().equals(Provider.activemq.toString())) {
        jmsComponent = ActiveMQComponent.activeMQComponent();
        jmsComponent.setConnectionFactory(new PooledConnectionFactory(this.getBrokerUrl()));
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    } else if (this.getProvider().equals(Provider.ibmmq.toString())) {
        JmsConnectionFactory factory = null;
        try {
            JmsFactoryFactory jmsFactoryFactory;
            jmsFactoryFactory = JmsFactoryFactory.getInstance(JmsConstants.WMQ_PROVIDER);
            factory = jmsFactoryFactory.createConnectionFactory();
            factory.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            factory.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, this.getQueueManager());
            factory.setStringProperty(WMQConstants.WMQ_HOST_NAME, this.getBrokerUrl());
            factory.setIntProperty(WMQConstants.WMQ_PORT, this.getPort());
            if (this.getChannel() != null && !this.getChannel().isEmpty())
                factory.setStringProperty(WMQConstants.WMQ_CHANNEL, this.getChannel());
            factory.setIntProperty(WMQConstants.DELIVERY_MODE, this.getDeliveryMode());
        } catch (JMSException e) {
            logger.error("Error connecting to JMS provider.", e);
            throw new ProcessModellingException("Error connecting to JMS provider.", e);
        }
        UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter();
        adapter.setTargetConnectionFactory(factory);
        if (this.getUserName() != null) {
            adapter.setUsername(this.getUserName());
        }
        if (this.getPassword() != null) {
            adapter.setPassword(this.getPassword());
        }
        jmsComponent = JmsComponent.jmsComponent();
        jmsComponent.setConnectionFactory(adapter);
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    } else {
        Hashtable<String, String> prop = new Hashtable<String, String>();
        // Mandatory property.
        prop.put(Context.PROVIDER_URL, this.getLdapConfiguration().getProviderUrl());
        prop.put(Context.INITIAL_CONTEXT_FACTORY, this.getLdapConfiguration().getInitialContextFactory());

        // Only these optional properties supported now.
        if (this.getLdapConfiguration().getSecurityAuthentication() != null) {
            prop.put(Context.SECURITY_AUTHENTICATION, this.getLdapConfiguration().getSecurityAuthentication());
        }
        if (this.getLdapConfiguration().getSecutiryPrincipal() != null) {
            prop.put(Context.SECURITY_PRINCIPAL, this.getLdapConfiguration().getSecutiryPrincipal());
        }
        if (this.getLdapConfiguration().getSecutiryCredentials() != null) {
            prop.put(Context.SECURITY_CREDENTIALS, this.getLdapConfiguration().getSecutiryCredentials());
        }
        Context context;
        ConnectionFactory connectionFactory;
        try {
            // HACK required to avoid ClassNotFoundException while
            // retrieving the
            // InitialContext.
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
                context = new InitialContext(prop);
                connectionFactory = (ConnectionFactory) context
                        .lookup(this.getLdapConfiguration().getConnectionFactoryJndiName());
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
            // HACK -- Finished
        } catch (NamingException e) {
            logger.error("Error connecting to JMS provider.", e);
            throw new ProcessModellingException("Error connecting to JMS provider.", e);
        }
        UserCredentialsConnectionFactoryAdapter adapter = new UserCredentialsConnectionFactoryAdapter();
        adapter.setTargetConnectionFactory(connectionFactory);
        if (this.getUserName() != null) {
            adapter.setUsername(this.getUserName());
        }
        if (this.getPassword() != null) {
            adapter.setPassword(this.getPassword());
        }
        jmsComponent = JmsComponent.jmsComponent();
        jmsComponent.setConnectionFactory(adapter);
        jmsComponent.setCamelContext(routeBuilder.getContext());
        jmsComponent.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
    }

    if (jmsComponent != null) {
        jmsComponent.setConcurrentConsumers(getThreadCount());
    }
    return jmsComponent;
}

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

/**
 * Sets the contexts for this base class.  Values of user and password used to
 * set the respective JNDI properties.  These values can be overriden by the
 * overrides properties./*from   ww  w . java  2 s .c o m*/
 *
 * @param user   the username for authenticating as this user
 * @param passwd the password of the user
 * @throws NamingException if there is a failure of any kind
 */
protected void setContexts(String user, String passwd) throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, passwd);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    setContexts(env);
}

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

@Test
public void testRunning() throws Exception {
    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, "simple");
    env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
    DirContext ctx = new InitialDirContext(env);

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

    NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

    while (list.hasMore()) {
        NameClassPair ncp = list.next();
        set.add(ncp.getName());/*from w  w w. j  a v  a  2 s . co m*/
    }

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

    ctx.close();
}

From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java

/**
 * Infer the root DN./*  w  w w .  j  a  v a2  s  .  co m*/
 *
 * @return null if not found.
 */
private String inferRootDN(String server) {
    try {
        Hashtable<String, String> props = new Hashtable<String, String>();
        if (managerDN != null) {
            props.put(Context.SECURITY_PRINCIPAL, managerDN);
            props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
        }
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, toProviderUrl(fixNull(getServerUrl()), ""));

        DirContext ctx = new InitialDirContext(props);
        Attributes atts = ctx.getAttributes("");
        Attribute a = atts.get("defaultNamingContext");
        if (a != null && a.get() != null) { // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
            return a.get().toString();
        }

        a = atts.get("namingcontexts");
        if (a == null) {
            LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
            return null;
        }
        return a.get().toString();
    } catch (NamingException e) {
        LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
        return null;
    }
}

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

/**
 * {@inheritDoc}//from w ww  .j ava  2 s  .  c o m
 */
@Override
public InitialDirContext getInitialDirContext(final String principal, final String credentials,
        final AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic
            : new AuthenticationDiagnostic();

    if (principal == null) {
        // failed before we tried to do anything
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Null user name provided.", effectiveDiagnostic);
    }

    if (principal.length() == 0) {
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Empty user name provided.", effectiveDiagnostic);
    }

    if (credentials == null) {
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("No credentials provided.", effectiveDiagnostic);
    }

    if (credentials.length() == 0) {
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Empty credentials provided.", effectiveDiagnostic);
    }

    effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, true, null);

    final Map<String, String> config = new HashMap<>(this.authenticatedEnvironment.size());
    config.putAll(this.authenticatedEnvironment);
    config.put(Context.SECURITY_PRINCIPAL, principal);
    config.put(Context.SECURITY_CREDENTIALS, credentials);

    final InitialDirContext initialDirContext = this.buildInitialDirContext(config, 0, effectiveDiagnostic);
    return initialDirContext;
}

From source file:ldap.ActiveLoginImpl.java

/**
 * open the directory connection.// www.j  a v a2  s. com
 * @param url
 * @param tracing
 * @return
 * @throws NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
     * First, set up a large number of environment variables to sensible default valuse
     */

    Hashtable env = new Hashtable();
    // sanity check
    if (url == null)
        throw new NamingException("URL not specified in openContext()!");

    // set the tracing level now, since it can't be set once the connection is open.
    if (tracing)
        env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output

    //env.put("java.naming.ldap.version", "3");               // always use ldap v3 - v2 too limited
    env.put(LdapConstants.ldapVersionStr, LdapConstants.ldapVersion); // always use ldap v3 - v2 too limited

    //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");  // use default jndi provider
    env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider

    //env.put("java.naming.ldap.deleteRDN", "false");         // usually what we want
    env.put(LdapConstants.ldapDeleteRdn, LdapConstants.ldapDeleteRdnValue); // usually what we want

    //env.put(Context.REFERRAL, "ignore");                    //could be: follow, ignore, throw
    env.put(Context.REFERRAL, LdapConstants.ldapIgnore); //could be: follow, ignore, throw

    // env.put("java.naming.ldap.derefAliases", "finding");    // could be: finding, searching, etc.
    env.put(LdapConstants.ldapFindingAliases, LdapConstants.ldapFindingStr); // could be: finding, searching, etc.

    //env.put(Context.SECURITY_AUTHENTICATION, "simple");         // 'simple' = username + password
    env.put(Context.SECURITY_AUTHENTICATION, LdapConstants.ldapSecurityAuth); // 'simple' = username + password

    env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn

    env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string-

    env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389"

    /*
     *  Open the actual LDAP session using the above environment variables
     */

    DirContext newContext = new InitialDirContext(env);

    if (newContext == null)
        throw new NamingException(
                "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");

    return newContext;

}