Example usage for javax.naming Context INITIAL_CONTEXT_FACTORY

List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY

Introduction

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

Prototype

String INITIAL_CONTEXT_FACTORY

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the initial context factory to use.

Usage

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

    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.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   w  w  w. j ava 2 s.c om*/
 *
 * @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.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java

/**
 * Infer the root DN.//from  w  w w . ja v a  2  s  . c  om
 *
 * @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:com.stimulus.archiva.security.realm.ADRealm.java

public ArrayList<AttributeValue> getADAttributes(Config config, ADIdentity identity, String username,
        String password) throws ArchivaException {
    logger.debug("getADAttributes()");
    validateLoginName(username);/*from  w  w w. j  a v  a2  s  . c  o  m*/
    validatePassword(password);
    LoginContext serverLC = kereberosLogin(config, identity, identity.getServiceDN(),
            identity.getServicePassword());
    Hashtable<String, String> env = new Hashtable<String, String>(11);
    String ldapAddress = identity.getLDAPAddress();
    if (!ldapAddress.toLowerCase(Locale.ENGLISH).startsWith("ldap://"))
        ldapAddress = "ldap://" + ldapAddress;
    logger.debug("finding DN of user from LDAP using Kereberos token {ldapAddress='" + ldapAddress
            + "', username='" + username + "'}");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapAddress);
    env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
    int at = username.indexOf('@');
    String uname = username;
    if (uname.indexOf("@") != -1) {
        uname = username.substring(0, at).toLowerCase(Locale.ENGLISH);
    }
    logger.debug("findUserDN {loginname='" + uname + "'}");
    String bindDN = null;
    try {
        bindDN = (String) Subject.doAs(serverLC.getSubject(), new FindDNAction(identity, uname, env));
    } catch (Exception e) {
        throw new ArchivaException("failed to bind to ldap server {uname='" + username + "''}", e, logger);
    }
    try {
        serverLC.logout();
    } catch (Exception e) {
        throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='"
                + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger);
    }
    ArrayList<AttributeValue> attributes = new ArrayList<AttributeValue>();
    serverLC = kereberosLogin(config, identity, username, password);
    if (bindDN != null) {
        env.clear();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapAddress);
        env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");

        try {
            attributes = (ArrayList<AttributeValue>) Subject.doAs(serverLC.getSubject(),
                    new GetAttributesAction(identity, username, env, bindDN));
        } catch (Exception e) {
            throw new ArchivaException("failed to bind to ldap server:" + e.getMessage() + " {uname='"
                    + username + "',ldapAddress='" + identity.getLDAPAddress() + "'}", e, logger);
        }
    }
    try {
        serverLC.logout();
    } catch (Exception e) {
        throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='"
                + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger);
    }
    logger.debug("getADAttributes() return");
    return attributes;

}

From source file:ru.efo.security.ADUserDetailsService.java

private DirContext getDirContext(String username, String password) throws NamingException {
    final Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.SECURITY_AUTHENTICATION, "simple");
    props.put(Context.SECURITY_PRINCIPAL, username);
    props.put(Context.SECURITY_CREDENTIALS, password);
    props.put(Context.PROVIDER_URL, ldapUrl);
    props.put("java.naming.ldap.attributes.binary", "objectSID");

    return new InitialDirContext(props);
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.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
 *
 * @param urlString//from w  ww .  j  a  va 2s  .  c om
 * @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 {

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes("");
        final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary");
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ldapBytes == null || ldapBytes.length == 0) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:net.grinder.util.NetworkUtils.java

public static List<String> getDnsServers() throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
    DirContext ctx = null;/*from  w ww . ja va2s.  c om*/
    List<String> dnsServers = new ArrayList<String>();
    try {
        ctx = new InitialDirContext(env);
        String dnsString = (String) ctx.getEnvironment().get("java.naming.provider.url");
        for (String each : dnsString.split(" ")) {
            dnsServers.add(each.replace("dns://", ""));
        }
    } catch (Exception e) {
        NoOp.noOp();
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
    return dnsServers;
}

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

@Test
public void testSaslGssapiLdapAuth() throws Exception {

    final 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, "GSSAPI");

    LoginContext loginContext = new LoginContext("broker-sasl-gssapi");
    loginContext.login();/*from   w ww .ja  v  a  2  s. c o  m*/
    try {
        Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> {

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

            DirContext ctx = new InitialDirContext(env);
            NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

            while (list.hasMore()) {
                NameClassPair ncp = list.next();
                set.add(ncp.getName());
            }

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

            ctx.close();
            return null;

        });
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Bind authenticate./*from  www .  ja v a  2  s .  c om*/
 *
 * @param username the user to be used
 * @param password the password to be used
 * @return true if the user was authenticated
 * @throws PortalServiceException for any errors encountered
 */
public boolean authenticate(String username, String password) throws PortalServiceException {
    DirContext ctx = null;
    try {
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, env.getProperty(Context.INITIAL_CONTEXT_FACTORY));
        props.put(Context.PROVIDER_URL, env.getProperty(Context.PROVIDER_URL));
        props.put(Context.SECURITY_PRINCIPAL, MessageFormat.format(userDNPattern, username));
        props.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialDirContext(props);
        return true;
    } catch (AuthenticationException authEx) {
        return false;
    } catch (NamingException e) {
        throw new PortalServiceException("Could not verify authentication results.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:com.adaptris.core.SharedComponentList.java

private Context getContext() throws CoreException {
    try {/*from   ww w .  ja va 2  s .co  m*/
        if (context == null) {
            Properties contextEnv = new Properties();
            contextEnv.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
            context = new InitialContext(contextEnv);
        }
    } catch (NamingException e) {
        throw ExceptionHelper.wrapCoreException(e);
    }
    return context;
}