Example usage for javax.naming.ldap InitialLdapContext InitialLdapContext

List of usage examples for javax.naming.ldap InitialLdapContext InitialLdapContext

Introduction

In this page you can find the example usage for javax.naming.ldap InitialLdapContext InitialLdapContext.

Prototype

@SuppressWarnings("unchecked")
public InitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException 

Source Link

Document

Constructs an initial context using environment properties and connection request controls.

Usage

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.LdapCommentAuthenticator.java

public boolean authenticate(HttpServletRequest request) {
    boolean validUser = false;
    LdapContext context = null;/*from  w  w  w  . j av  a 2  s . c  o  m*/

    String ldapDc = WebloggerConfig.getProperty("comment.authenticator.ldap.dc");
    String ldapOu = WebloggerConfig.getProperty("comment.authenticator.ldap.ou");
    String ldapPort = WebloggerConfig.getProperty("comment.authenticator.ldap.port");
    String ldapHost = WebloggerConfig.getProperty("comment.authenticator.ldap.host");
    String ldapSecurityLevel = WebloggerConfig.getProperty("comment.authenticator.ldap.securityLevel");

    boolean rollerPropertiesValid = validateRollerProperties(ldapDc, ldapOu, ldapPort, ldapHost);

    String ldapUser = request.getParameter("ldapUser");
    String ldapPass = request.getParameter("ldapPass");

    boolean userDataValid = validateUsernamePass(ldapUser, ldapPass);

    if (rollerPropertiesValid && userDataValid) {
        try {
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            if (ldapSecurityLevel != null && (ldapSecurityLevel.equalsIgnoreCase("none")
                    || ldapSecurityLevel.equalsIgnoreCase("simple")
                    || ldapSecurityLevel.equalsIgnoreCase("strong"))) {
                env.put(Context.SECURITY_AUTHENTICATION, ldapSecurityLevel);
            }
            env.put(Context.SECURITY_PRINCIPAL, getQualifedDc(ldapDc, ldapOu, ldapUser));
            env.put(Context.SECURITY_CREDENTIALS, ldapPass);
            env.put(Context.PROVIDER_URL, "ldap://" + ldapHost + ":" + ldapPort);
            context = new InitialLdapContext(env, null);
            validUser = true;
            LOG.info("LDAP Authentication Successful. user: " + ldapUser);
        } catch (Exception e) {
            // unexpected
            LOG.error(e);
        } finally {
            if (context != null) {
                try {
                    context.close();
                } catch (NamingException e) {
                    LOG.error(e);
                }
            }
        }
    }
    return validUser;
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided
 * username and credential.//from   ww  w  . j a va  2 s .  com
 *
 * @return the Initial Ldap Context to be used to perform searches, etc.
 * @throws NamingException LDAP binding error.
 */
protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential)
        throws NamingException {

    Properties env = new Properties();

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication());
    env.setProperty(Context.PROVIDER_URL, getProviderUrl());
    env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol()));

    // Set defaults for key values if they are missing

    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
    }

    String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);

    if (authType == null)
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");

    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    String providerURL = getProviderUrl();
    // Use localhost if providerUrl not set
    if (providerURL == null) {
        providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
    } else {
        // In case user configured provided URL
        if (providerURL.startsWith("ldaps")) {
            protocol = "ssl";
            env.setProperty(Context.SECURITY_PROTOCOL, "ssl");
        }

    }

    env.setProperty(Context.PROVIDER_URL, providerURL);

    if (securityPrincipal != null && !"".equals(securityPrincipal))
        env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);

    if (securityCredential != null && !"".equals(securityCredential))
        env.put(Context.SECURITY_CREDENTIALS, securityCredential);

    // always follow referrals transparently
    env.put(Context.REFERRAL, "follow");

    // Logon into LDAP server
    if (logger.isDebugEnabled())
        logger.debug("Logging into LDAP server, env=" + env);

    InitialLdapContext ctx = new InitialLdapContext(env, null);

    if (logger.isDebugEnabled())
        logger.debug("Logged into LDAP server, " + ctx);

    return ctx;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private LdapContext getLdapContext() throws NamingException, AuthenticationException {
    if (config == null) {
        throw new NamingException("LDAP not configured");
    }/*w w w. j  a v a2s .  com*/
    if (StringUtils.isBlank(config.getProviderUrl())) {
        throw new NamingException("No LDAP server available");
    }
    if (StringUtils.isBlank(config.getUsername()) || StringUtils.isBlank(config.getPassword())) {
        throw new AuthenticationException("No LDAP credentials available");
    }
    String ctxFactory = config.getCtxFactory();
    if (StringUtils.isBlank(ctxFactory)) {
        ctxFactory = DEFAULT_CONTEXT_FACTORY;
    }
    String authentication = config.getAuthentication();
    if (StringUtils.isBlank(authentication)) {
        authentication = SIMPLE_AUTHENTICATION;
    }

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFactory);
    env.put(Context.PROVIDER_URL, config.getProviderUrl());
    env.put(Context.SECURITY_PRINCIPAL, config.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, config.getPassword());
    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (StringUtils.isNotBlank(config.getReferral())) {
        env.put(Context.REFERRAL, config.getReferral());
    }
    if (config.getProviderUrl().startsWith(LDAPS_SCHEME)) {
        env.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$
        if (config.isSslNoVerify()) {
            env.put(JNDI_SOCKET_FACTORY, LDAPTrustAllSocketFactory.class.getName());
        }
    }
    // Gemini-specific properties
    env.put(JNDIConstants.BUNDLE_CONTEXT, FrameworkUtil.getBundle(LDAPClient.class).getBundleContext());

    // com.sun.jndi.ldap.LdapCtxFactory specific properties
    env.put(READ_TIMEOUT, DEFAULT_READ_TIMEOUT);
    env.put(USE_CONNECTION_POOLING, "true"); //$NON-NLS-1$

    // extremly ugly classloading workaround:
    // com.sun.jndi.ldap.LdapCtxFactory uses Class.forName() to load the socket factory, shame on them!
    InitialLdapContext ctx = null;
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(LDAPTrustAllSocketFactory.class.getClassLoader());
        ctx = new InitialLdapContext(env, null);
    } finally {
        if (classloader != null) {
            Thread.currentThread().setContextClassLoader(classloader);
        }
    }
    return ctx;
}

From source file:org.exist.security.realm.ldap.LdapContextFactory.java

public LdapContext getLdapContext(String username, final String password,
        final Map<String, Object> additionalEnv) throws NamingException {

    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }/*www. jav a 2s.  c o  m*/

    if (StringUtils.isBlank(password)) {
        throw new IllegalStateException("Password for LDAP authentication may not be empty.");
    }

    if (username != null && principalPattern != null) {
        username = principalPatternFormat.format(new String[] { username });
    }

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

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

    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }

    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);

    //Absolutely nessecary for working with Active Directory
    env.put("java.naming.ldap.attributes.binary", "objectSid");

    // the following is helpful in debugging errors
    //env.put("com.sun.jndi.ldap.trace.ber", System.err);

    // Only pool connections for system contexts
    if (usePooling && username != null && username.equals(systemUsername)) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }

    if (additionalEnv != null) {
        env.putAll(additionalEnv);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Initializing LDAP context using URL [" + url + "] and username [" + username + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }

    return new InitialLdapContext(env, null);
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

public LdapContext getLdapContext() throws NamingException {
    return new DummyLdapContext(new InitialLdapContext(new Hashtable<String, Object>(env), null));
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

public InitialContext getInitialContext() throws NamingException {
    Hashtable<String, Object> props = new Hashtable<String, Object>(env);
    props.put(Context.OBJECT_FACTORIES, "com.sun.jndi.ldap.obj.LdapGroupFactory");
    props.put(Context.STATE_FACTORIES, "com.sun.jndi.ldap.obj.LdapGroupFactory");
    return new DummyLdapContext(new InitialLdapContext(props, null));
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

public boolean authenticate(String userDN, String password) throws NamingException {
    Hashtable<String, Object> props = new Hashtable<String, Object>(env);
    props.put(Context.SECURITY_AUTHENTICATION, "simple");
    props.put(Context.SECURITY_PRINCIPAL, userDN);
    props.put(Context.SECURITY_CREDENTIALS, password);
    props.put("com.sun.jndi.ldap.connect.pool", "false");

    InitialContext ctx = null;/*  www  .  ja v a  2s  . co m*/
    try {
        ctx = new DummyLdapContext(new InitialLdapContext(props, null));
        return true;
    } catch (NamingException e) {
        LOG.debug("Error during initialization LDAP Context", e);
        return false;
    } finally {
        closeContext(ctx);
    }
}

From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java

public void collect() {

    // Setup initial LDAP properties
    Properties env = new Properties();
    Properties props = getProperties();

    // Set our default factory name if one is not given
    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    }/*from   w  ww .j  a v  a2s  .c  o  m*/

    // Set the LDAP url
    if (isSSL()) {
        env.put("java.naming.ldap.factory.socket", LDAPSSLSocketFactory.class.getName());
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    String providerUrl = "ldap://" + getHostname() + ":" + getPort();
    env.setProperty(Context.PROVIDER_URL, providerUrl);

    // For log track
    setSource(providerUrl);

    // Follow referrals automatically
    env.setProperty(Context.REFERRAL, "follow");

    // Base DN
    String baseDN = props.getProperty(PROP_BASEDN);
    if (baseDN == null) {
        setErrorMessage("No Base DN given, refusing login");
        setAvailability(false);
        return;
    }

    // Search filter
    String filter = props.getProperty(PROP_FILTER);

    // Load any information we may need to bind
    String bindDN = props.getProperty(PROP_BINDDN);
    String bindPW = props.getProperty(PROP_BINDPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    if (log.isDebugEnabled()) {
        log.debug("Using LDAP environment: " + env);
    }

    try {
        startTime();
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        endTime();

        setAvailability(true);

        // If a search filter is specified, run the search and return the
        // number of matches as a metric
        if (filter != null) {
            log.debug("Using LDAP filter=" + filter);
            NamingEnumeration answer = ctx.search(baseDN, filter, getSearchControls());

            long matches = 0;
            while (answer.hasMore()) {
                matches++;
                answer.next();
            }

            setValue("NumberofMatches", matches);
        }
    } catch (Exception e) {
        setAvailability(false);
        if (log.isDebugEnabled()) {
            log.debug("LDAP check failed: " + e, e);
        }

        setErrorMessage("LDAP check failed: " + e);
    }
}

From source file:org.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *//*w  ww  . j  a va2s  .  c  o  m*/
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
                new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute",
                Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }

    namingEnum.close();
    ctx.close();
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided
 * username and credential.//from w  w w  .j  a  va2 s . c o  m
 *
 * @return the Initial Ldap Context to be used to perform searches, etc.
 * @throws NamingException LDAP binding error.
 */
protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential)
        throws NamingException {

    Properties env = new Properties();

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication());
    env.setProperty(Context.PROVIDER_URL, getProviderUrl());
    env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol()));

    // Set defaults for key values if they are missing

    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
    }

    String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
    if (authType == null)
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");

    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    String providerURL = getProviderUrl();
    // Use localhost if providerUrl not set
    if (providerURL == null) {
        //providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
        if (protocol != null && protocol.equals("ssl")) {
            // We should use Start TLS extension?
            providerURL = "ldaps://localhost:636";
        } else {
            providerURL = "ldap://localhost:389";
        }
    }

    env.setProperty(Context.PROVIDER_URL, providerURL);
    env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredential);

    // always follow referrals transparently
    env.put(Context.REFERRAL, "follow");

    // Logon into LDAP server
    if (logger.isDebugEnabled())
        logger.debug("Logging into LDAP server, env=" + env);

    InitialLdapContext ctx = new InitialLdapContext(env, null);

    if (logger.isDebugEnabled())
        logger.debug("Logged into LDAP server, " + ctx);

    return ctx;
}