Search in sources :

Example 1 with DirContext

use of javax.naming.directory.DirContext in project camel by apache.

the class LdapProducer method process.

public void process(Exchange exchange) throws Exception {
    String filter = exchange.getIn().getBody(String.class);
    DirContext dirContext = getDirContext();
    try {
        // could throw NamingException
        List<SearchResult> data;
        if (pageSize == null) {
            data = simpleSearch(dirContext, filter);
        } else {
            if (!(dirContext instanceof LdapContext)) {
                throw new IllegalArgumentException("When using attribute 'pageSize' for a ldap endpoint, you must provide a LdapContext (subclass of DirContext)");
            }
            data = pagedSearch((LdapContext) dirContext, filter);
        }
        exchange.getOut().setBody(data);
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());
        exchange.getOut().setAttachments(exchange.getIn().getAttachments());
    } finally {
        if (dirContext != null) {
            dirContext.close();
        }
    }
}
Also used : SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext) LdapContext(javax.naming.ldap.LdapContext)

Example 2 with DirContext

use of javax.naming.directory.DirContext in project hadoop by apache.

the class LdapGroupsMapping method doGetGroups.

/**
   * Perform LDAP queries to get group names of a user.
   *
   * Perform the first LDAP query to get the user object using the user's name.
   * If one-query is enabled, retrieve the group names from the user object.
   * If one-query is disabled, or if it failed, perform the second query to
   * get the groups.
   *
   * @param user user name
   * @return a list of group names for the user. If the user can not be found,
   * return an empty string array.
   * @throws NamingException if unable to get group names
   */
List<String> doGetGroups(String user, int goUpHierarchy) throws NamingException {
    DirContext c = getDirContext();
    // Search for the user. We'll only ever need to look at the first result
    NamingEnumeration<SearchResult> results = c.search(baseDN, userSearchFilter, new Object[] { user }, SEARCH_CONTROLS);
    // return empty list if the user can not be found.
    if (!results.hasMoreElements()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("doGetGroups(" + user + ") returned no groups because the " + "user is not found.");
        }
        return new ArrayList<String>();
    }
    SearchResult result = results.nextElement();
    List<String> groups = null;
    if (useOneQuery) {
        try {
            /**
         * For Active Directory servers, the user object has an attribute
         * 'memberOf' that represents the DNs of group objects to which the
         * user belongs. So the second query may be skipped.
         */
            Attribute groupDNAttr = result.getAttributes().get(memberOfAttr);
            if (groupDNAttr == null) {
                throw new NamingException("The user object does not have '" + memberOfAttr + "' attribute." + "Returned user object: " + result.toString());
            }
            groups = new ArrayList<String>();
            NamingEnumeration groupEnumeration = groupDNAttr.getAll();
            while (groupEnumeration.hasMore()) {
                String groupDN = groupEnumeration.next().toString();
                groups.add(getRelativeDistinguishedName(groupDN));
            }
        } catch (NamingException e) {
            // If the first lookup failed, fall back to the typical scenario.
            LOG.info("Failed to get groups from the first lookup. Initiating " + "the second LDAP query using the user's DN.", e);
        }
    }
    if (groups == null || groups.isEmpty() || goUpHierarchy > 0) {
        groups = lookupGroup(result, c, goUpHierarchy);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("doGetGroups(" + user + ") returned " + groups);
    }
    return groups;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) NamingEnumeration(javax.naming.NamingEnumeration) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext)

Example 3 with DirContext

use of javax.naming.directory.DirContext in project hadoop by apache.

the class DNS method reverseDns.

/**
   * Returns the hostname associated with the specified IP address by the
   * provided nameserver.
   *
   * Loopback addresses 
   * @param hostIp The address to reverse lookup
   * @param ns The host name of a reachable DNS server
   * @return The host name associated with the provided IP
   * @throws NamingException If a NamingException is encountered
   */
public static String reverseDns(InetAddress hostIp, @Nullable String ns) throws NamingException {
    //
    // Builds the reverse IP lookup form
    // This is formed by reversing the IP numbers and appending in-addr.arpa
    //
    String[] parts = hostIp.getHostAddress().split("\\.");
    String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa";
    DirContext ictx = new InitialDirContext();
    Attributes attribute;
    try {
        attribute = ictx.getAttributes(// Use "dns:///" if the default
        "dns://" + ((ns == null) ? "" : ns) + // nameserver is to be used
        "/" + reverseIP, new String[] { "PTR" });
    } finally {
        ictx.close();
    }
    String hostname = attribute.get("PTR").get().toString();
    int hostnameLength = hostname.length();
    if (hostname.charAt(hostnameLength - 1) == '.') {
        hostname = hostname.substring(0, hostnameLength - 1);
    }
    return hostname;
}
Also used : Attributes(javax.naming.directory.Attributes) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 4 with DirContext

use of javax.naming.directory.DirContext in project tomcat by apache.

the class JNDIRealm method getPrincipal.

@Override
protected Principal getPrincipal(String username, GSSCredential gssCredential) {
    DirContext context = null;
    Principal principal = null;
    try {
        // Ensure that we have a directory context available
        context = open();
        // time before giving up.
        try {
            // Authenticate the specified username if possible
            principal = getPrincipal(context, username, gssCredential);
        } catch (CommunicationException | ServiceUnavailableException e) {
            // log the exception so we know it's there.
            containerLog.info(sm.getString("jndiRealm.exception.retry"), e);
            // close the connection so we know it will be reopened.
            if (context != null)
                close(context);
            // open a new directory context.
            context = open();
            // Try the authentication again.
            principal = getPrincipal(context, username, gssCredential);
        }
        // Release this context
        release(context);
        // Return the authenticated Principal (if any)
        return principal;
    } catch (NamingException e) {
        // Log the problem for posterity
        containerLog.error(sm.getString("jndiRealm.exception"), e);
        // Close the connection so that it gets reopened next time
        if (context != null)
            close(context);
        // Return "not authenticated" for this request
        return null;
    }
}
Also used : CommunicationException(javax.naming.CommunicationException) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) ServiceUnavailableException(javax.naming.ServiceUnavailableException) Principal(java.security.Principal)

Example 5 with DirContext

use of javax.naming.directory.DirContext in project tomcat by apache.

the class TestJNDIRealm method mockDirContext.

private DirContext mockDirContext(NamingEnumeration<SearchResult> namingEnumeration) throws NamingException {
    DirContext dirContext = EasyMock.createNiceMock(InitialDirContext.class);
    EasyMock.expect(dirContext.search(EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyObject(SearchControls.class))).andReturn(namingEnumeration).times(2);
    EasyMock.expect(dirContext.getNameParser("")).andReturn(new NameParserImpl()).times(2);
    EasyMock.expect(dirContext.getNameInNamespace()).andReturn("ANY NAME").times(2);
    EasyMock.replay(dirContext);
    return dirContext;
}
Also used : NameParserImpl(org.apache.naming.NameParserImpl) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Aggregations

DirContext (javax.naming.directory.DirContext)76 NamingException (javax.naming.NamingException)32 InitialDirContext (javax.naming.directory.InitialDirContext)32 SearchResult (javax.naming.directory.SearchResult)26 SearchControls (javax.naming.directory.SearchControls)22 Attributes (javax.naming.directory.Attributes)18 Attribute (javax.naming.directory.Attribute)16 NamingEnumeration (javax.naming.NamingEnumeration)14 Test (org.junit.Test)14 Hashtable (java.util.Hashtable)12 DistinguishedName (org.springframework.ldap.core.DistinguishedName)11 Name (javax.naming.Name)7 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 BasicAttributes (javax.naming.directory.BasicAttributes)6 Authentication (org.springframework.security.core.Authentication)5 Principal (java.security.Principal)3 LdapContext (javax.naming.ldap.LdapContext)3