Example usage for javax.naming Context SECURITY_AUTHENTICATION

List of usage examples for javax.naming Context SECURITY_AUTHENTICATION

Introduction

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

Prototype

String SECURITY_AUTHENTICATION

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the security level to use.

Usage

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

@Override
public boolean authenticate(String id, char[] password) {
    if (id == null || id.isEmpty())
        return false;

    if (idSuffix != null)
        id = id + idSuffix;/* w  w w. j a va2s .c  o  m*/

    String cachedPassword = credentialCache.get(id);
    String encodedPassword = null;

    try {
        encodedPassword = codec.encode(new String(password));
    } catch (EncoderException e1) {
    }

    if (cachedPassword != null && encodedPassword != null && cachedPassword.equals(encodedPassword))
        return true;

    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, url);
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");
    environment.put(Context.SECURITY_PRINCIPAL, id);
    environment.put(Context.SECURITY_CREDENTIALS, new String(password));

    try {
        InitialDirContext context = new InitialDirContext(environment);
        context.close();

        if (encodedPassword != null)
            credentialCache.put(id, encodedPassword);

        return true;
    } catch (NamingException e) {
        return false;
    }
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

void activate(Map<?, ?> configuration) throws NamingException {
    this.idSuffix = (String) configuration.get(CONFIG_ID_SUFFIX);
    this.url = (String) configuration.get(CONFIG_URL);
    this.baseDN = (String) configuration.get(CONFIG_BASE_DN);
    this.userSearchBase = (String) configuration.get(CONFIG_USER_SEARCH_BASE);
    this.userFilter = (String) configuration.get(CONFIG_USER_FILTER);

    String managerDN = (String) configuration.get(CONFIG_MANAGER_DN);
    String managerPassword = (String) configuration.get(CONFIG_MANAGER_PASSWORD);

    searchEnvironment = new Hashtable<String, String>();
    searchEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    searchEnvironment.put(Context.PROVIDER_URL, url);

    if (managerDN != null) {
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        searchEnvironment.put(Context.SECURITY_PRINCIPAL, managerDN);
        searchEnvironment.put(Context.SECURITY_CREDENTIALS, managerPassword);
    } else/*from w w  w  .j a va 2  s  . c  o m*/
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "none");
}

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>");
    }/*from   w w w. j  a  va 2  s.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 DummyLDAPServiceImpl() throws Exception {
    File workingDirectory = new File("target/working-server");
    workingDirectory.mkdirs();/*from ww w.  ja  v  a2s  .c  o m*/

    doDelete(workingDirectory);

    // Initialize the LDAP service
    service = new DefaultDirectoryService();
    service.setWorkingDirectory(workingDirectory);

    // first load the schema
    initSchemaPartition();

    // then the system partition
    // this is a MANDATORY partition
    Partition systemPartition = addPartition("system", ServerDNConstants.SYSTEM_DN);
    service.setSystemPartition(systemPartition);

    // Disable the ChangeLog system
    service.getChangeLog().setEnabled(false);

    // Create a new partition
    Partition partition = addPartition("eXoTestPartition", "dc=exoplatform,dc=org");

    // Index some attributes on the partition
    addIndex(partition, "objectClass", "ou", "uid");

    service.setShutdownHookEnabled(false);

    service.startup();

    // Inject the eXo root entry if it does not already exist
    if (!service.getAdminSession().exists(partition.getSuffixDn())) {
        DN dnExo = new DN("dc=exoplatform,dc=org");
        ServerEntry entryExo = service.newEntry(dnExo);
        entryExo.add("objectClass", "top", "domain", "extensibleObject");
        entryExo.add("dc", "exoplatform");
        service.getAdminSession().add(entryExo);
    }

    port = AvailablePortFinder.getNextAvailable(1024);
    server = new LdapServer();
    server.setTransports(new TcpTransport(port));
    server.setDirectoryService(service);
    server.start();

    // server launched and configured

    // configuration of client side
    env.put(DirectoryService.JNDI_KEY, service);
    env.put(Context.PROVIDER_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, CoreContextFactory.class.getName());

    // Add the new schema needed for COR-293
    addNewSchema();
}

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;/*from w ww  . ja va  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.gbif.portal.registration.LDAPUtils.java

/**
 * Get LDAP context.// www.j av  a2  s .c o  m
 * @param url
 * @return
 * @throws NamingException
 */
public DirContext getContext(String url) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    env.put(Context.SECURITY_AUTHENTICATION, authenticationType);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
    DirContext ctx = new InitialDirContext(env);
    return 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 ww w  .j  av  a  2 s .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.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

public DirContext getDirContext(Properties props) throws NamingException {
    if (this.ctx == null) {
        synchronized (this) {
            if (this.ctx == null) {
                log.debug("[getDirContext] creating new connection");
                Collection rtn = new TreeSet();
                Hashtable ldapEnv = new Hashtable();
                String ldapDriver = props.getProperty("ldapDriver"),
                        ldapHostURL = props.getProperty("ldapHostURL"),
                        ldapAuthType = props.getProperty("ldapAuthType"),
                        ldapPasswd = props.getProperty("ldapPasswd"),
                        ldapTreePathToDN = props.getProperty("ldapTreePathToDN");
                ldapTreePathToDN = (ldapTreePathToDN == null) ? "" : ldapTreePathToDN;
                ldapPasswd = (ldapPasswd == null) ? "" : ldapPasswd;
                ldapPasswd = (ldapPasswd.matches("^\\s*$")) ? "" : ldapPasswd;
                ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapDriver);
                ldapEnv.put(Context.PROVIDER_URL, ldapHostURL);
                ldapEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthType);
                ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapTreePathToDN);
                ldapEnv.put(Context.SECURITY_CREDENTIALS, ldapPasswd);
                this.ctx = new InitialDirContext(ldapEnv);
            }//from  w  w w.j  a  v a2 s. c  om
        }
    }
    return this.ctx;
}

From source file:org.jamwiki.ldap.LdapUserHandler.java

/**
 * Connect to the LDAP server and return a context.
 *
 * @return The LDAP context to use when retrieving user information.
 *//*w ww .  j  ava2 s  . c  o  m*/
private InitialDirContext getContext(String username, String password) throws Exception {
    // Set up the environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, Environment.getValue(Environment.PROP_LDAP_FACTORY_CLASS));
    env.put(Context.PROVIDER_URL, Environment.getValue(Environment.PROP_LDAP_URL));
    if (!StringUtils.isBlank(username)) {
        // "simple" "DIGEST-MD5"
        env.put(Context.SECURITY_AUTHENTICATION,
                Environment.getValue(Environment.PROP_LDAP_SECURITY_AUTHENTICATION));
        // cn=login, ou=NewHires, o=JNDITutorial
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    InitialDirContext ctx = new InitialDirContext(env);
    return ctx;
}

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 av a  2  s. c om*/
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();
}