Search in sources :

Example 96 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project wildfly by wildfly.

the class ExternalContextBindingTestCase method testWithActualLDAPContext.

private void testWithActualLDAPContext(boolean withCache) throws Exception {
    InitialContext ctx = null;
    InitialDirContext ldapContext1 = null;
    InitialDirContext ldapContext2 = null;
    try {
        ctx = new InitialContext();
        String initialDirContext = withCache ? "java:global/ldap-cache" : "java:global/ldap";
        LOGGER.debug("looking up " + initialDirContext + " ....");
        ldapContext1 = (InitialDirContext) ctx.lookup(initialDirContext);
        ldapContext2 = (InitialDirContext) ctx.lookup(initialDirContext);
        Assert.assertNotNull(ldapContext1);
        Assert.assertNotNull(ldapContext2);
        if (withCache) {
            Assert.assertSame(ldapContext1, ldapContext2);
        } else {
            Assert.assertNotSame(ldapContext1, ldapContext2);
        }
        LOGGER.debug("acquired external LDAP context: " + ldapContext1.toString());
        LdapContext c = (LdapContext) ldapContext1.lookup("dc=jboss,dc=org");
        c = (LdapContext) c.lookup("ou=People");
        Attributes attributes = c.getAttributes("uid=jduke");
        Assert.assertTrue(attributes.get("description").contains("awesome"));
        // resource injection
        LookupEjb ejb = (LookupEjb) ctx.lookup("java:module/LookupEjb");
        Assert.assertNotNull(ejb);
        c = ejb.getLdapCtx();
        Assert.assertNotNull(c);
        c = (LdapContext) c.lookup("ou=People");
        attributes = c.getAttributes("uid=jduke");
        Assert.assertTrue(attributes.get("description").contains("awesome"));
    } finally {
        if (ctx != null) {
            ctx.close();
        }
        if (ldapContext1 != null) {
            ldapContext1.close();
        }
        if (ldapContext2 != null) {
            ldapContext2.close();
        }
    }
}
Also used : Attributes(javax.naming.directory.Attributes) InitialDirContext(javax.naming.directory.InitialDirContext) InitialContext(javax.naming.InitialContext) LdapContext(javax.naming.ldap.LdapContext)

Example 97 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project mongo-java-driver by mongodb.

the class DefaultDnsResolver method resolveAdditionalQueryParametersFromTxtRecords.

/*
      A TXT record is just a string
      We require each to be one or more query parameters for a MongoDB connection string.
      Here we concatenate TXT records together with a '&' separator as required by connection strings
    */
@Override
public String resolveAdditionalQueryParametersFromTxtRecords(final String host) {
    String additionalQueryParameters = "";
    InitialDirContext dirContext = createDnsDirContext();
    try {
        Attributes attributes = dirContext.getAttributes(host, new String[] { "TXT" });
        Attribute attribute = attributes.get("TXT");
        if (attribute != null) {
            NamingEnumeration<?> txtRecordEnumeration = attribute.getAll();
            if (txtRecordEnumeration.hasMore()) {
                // Remove all space characters, as the DNS resolver for TXT records inserts a space character
                // between each character-string in a single TXT record.  That whitespace is spurious in
                // this context and must be removed
                additionalQueryParameters = ((String) txtRecordEnumeration.next()).replaceAll("\\s", "");
                if (txtRecordEnumeration.hasMore()) {
                    throw new MongoConfigurationException(format("Multiple TXT records found for host '%s'.  Only one is permitted", host));
                }
            }
        }
    } catch (NamingException e) {
        throw new MongoConfigurationException("Unable to look up TXT record for host " + host, e);
    } finally {
        try {
            dirContext.close();
        } catch (NamingException e) {
        // ignore
        }
    }
    return additionalQueryParameters;
}
Also used : MongoConfigurationException(com.mongodb.MongoConfigurationException) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 98 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project mongo-java-driver by mongodb.

the class DefaultDnsResolver method createDnsDirContext.

/*
      It's unfortunate that we take a runtime dependency on com.sun.jndi.dns.DnsContextFactory.
      This is not guaranteed to work on all JVMs but in practice is expected to work on most.
    */
private static InitialDirContext createDnsDirContext() {
    Hashtable<String, String> envProps = new Hashtable<String, String>();
    envProps.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
    try {
        return new InitialDirContext(envProps);
    } catch (NamingException e) {
        // Just in case the provider url default has been changed to a non-dns pseudo url, fallback to the JDK default
        envProps.put(Context.PROVIDER_URL, "dns:");
        try {
            return new InitialDirContext(envProps);
        } catch (NamingException ex) {
            throw new MongoClientException("Unable to support mongodb+srv// style connections as the 'com.sun.jndi.dns.DnsContextFactory' " + "class is not available in this JRE. A JNDI context is required for resolving SRV records.", e);
        }
    }
}
Also used : MongoClientException(com.mongodb.MongoClientException) Hashtable(java.util.Hashtable) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 99 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project Payara by payara.

the class LDAPRealm method bindAsUser.

/**
 * Attempt to bind as a specific DN.
 */
private boolean bindAsUser(String bindDN, char[] password) {
    boolean bindSuccessful = false;
    Properties bindProperties = getLdapBindProps();
    bindProperties.put(SECURITY_PRINCIPAL, bindDN);
    bindProperties.put(SECURITY_CREDENTIALS, new String(password));
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(bindProperties);
        bindSuccessful = true;
    } catch (Exception e) {
        if (_logger.isLoggable(FINEST)) {
            _logger.log(FINEST, "Error binding to directory as: {0}", bindDN);
            _logger.log(FINEST, "Exception from JNDI: {0}", e.toString());
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return bindSuccessful;
}
Also used : NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) Properties(java.util.Properties) LoginException(javax.security.auth.login.LoginException) BadRealmException(com.sun.enterprise.security.auth.realm.BadRealmException) NamingException(javax.naming.NamingException) NoSuchRealmException(com.sun.enterprise.security.auth.realm.NoSuchRealmException) InvalidOperationException(com.sun.enterprise.security.auth.realm.InvalidOperationException) NoSuchUserException(com.sun.enterprise.security.auth.realm.NoSuchUserException)

Example 100 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project Payara by payara.

the class LDAPRealm method getGroups.

private List<String> getGroups(String userDN) {
    // no authentication has happened through the realm.
    DirContext ctx = null;
    String srcFilter = null;
    String dynFilter = null;
    String dynMember = getProperty(PARAM_DYNAMIC_GRP_TARGET);
    try {
        ctx = new InitialDirContext(getLdapBindProps());
        String _username = userDN;
        // Ignoring the exception to suppot simple group names as userDN
        LdapName name = new LdapName(userDN);
        // Issue GLASSFISH-19595
        for (Rdn rdn : name.getRdns()) {
            if (rdn.getType().equalsIgnoreCase(OID.CN.getName())) {
                _username = rdn.getValue().toString();
                break;
            }
        }
        if (_username == null && userDN != null && userDN.startsWith("uid")) {
            // handle uid=XXX here where cn is not present
            // TODO :maybe there is a better way to handle this??
            int first = userDN.indexOf("uid=");
            int last = userDN.indexOf(",");
            if (first != -1 && last != -1) {
                _username = userDN.substring(first + 4, last);
            }
        }
        StringBuilder sb = new StringBuilder(getProperty(PARAM_GRP_SEARCH_FILTER));
        StringBuilder dynSb = new StringBuilder(getProperty(PARAM_DYNAMIC_GRP_FILTER));
        substitute(sb, SUBST_SUBJECT_NAME, _username);
        substitute(sb, SUBST_SUBJECT_DN, userDN);
        substitute(dynSb, SUBST_SUBJECT_NAME, _username);
        substitute(dynSb, SUBST_SUBJECT_DN, userDN);
        srcFilter = sb.toString();
        dynFilter = dynSb.toString();
        List<String> groupsList = new ArrayList<>();
        groupsList.addAll(groupSearch(ctx, getProperty(PARAM_GRPDN), srcFilter, getProperty(PARAM_GRP_TARGET)));
        // search filter is constructed internally as
        // as a groupofURLS
        groupsList.addAll(dynamicGroupSearch(ctx, getProperty(PARAM_GRPDN), dynMember, dynFilter, getProperty(PARAM_GRP_TARGET)));
        return groupsList;
    } catch (Exception e) {
        groupSearchLogger.log(WARNING, "ldaprealm.groupsearcherror", e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                _logger.log(WARNING, "ldaprealm.exception", e);
            }
        }
    }
    return null;
}
Also used : ArrayList(java.util.ArrayList) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) Rdn(javax.naming.ldap.Rdn) LoginException(javax.security.auth.login.LoginException) BadRealmException(com.sun.enterprise.security.auth.realm.BadRealmException) NamingException(javax.naming.NamingException) NoSuchRealmException(com.sun.enterprise.security.auth.realm.NoSuchRealmException) InvalidOperationException(com.sun.enterprise.security.auth.realm.InvalidOperationException) NoSuchUserException(com.sun.enterprise.security.auth.realm.NoSuchUserException) LdapName(javax.naming.ldap.LdapName)

Aggregations

InitialDirContext (javax.naming.directory.InitialDirContext)131 DirContext (javax.naming.directory.DirContext)71 NamingException (javax.naming.NamingException)67 Hashtable (java.util.Hashtable)51 Attributes (javax.naming.directory.Attributes)34 Attribute (javax.naming.directory.Attribute)24 SearchResult (javax.naming.directory.SearchResult)22 SearchControls (javax.naming.directory.SearchControls)19 IOException (java.io.IOException)11 CommunicationException (javax.naming.CommunicationException)11 Test (org.junit.Test)11 Properties (java.util.Properties)10 BasicAttributes (javax.naming.directory.BasicAttributes)9 ArrayList (java.util.ArrayList)8 LoginException (javax.security.auth.login.LoginException)8 NameClassPair (javax.naming.NameClassPair)7 HashSet (java.util.HashSet)6 NamingEnumeration (javax.naming.NamingEnumeration)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)5