1
votes

Its been a day since I started working with Active Directory LDAP with Tomcat server.

I have not seen a clear and simple example (like a login module) of using Active Directory LDAP with Tomcat and moreover I just got the below details from the Administrator for the LDAP server that I access.

The below code looks simple, but I am stuck with the below exception.

  1. String server = "192.168.71.116"; // Server hostname
  2. int port = 50001;
  3. String basedn = "DC=cblan-test,DC=mblox,DC=com";

I pass in the username and password which are picked from the request object.

This is the main piece of code that I use, I got this example from here

<%
    String user = request.getParameter("user");
    String password = request.getParameter("password");

    String filter = "(|(uid=" + user + ")" + "(mail=" + user + "@*))";
    String cliEquiv = "<tt>ldapsearch -h " + server + " -p " +
            port + " -b " + basedn + " \"" + filter + "\"</tt></p>";
    %>
    <p>Equivalent command line:<br /><%= cliEquiv%><hr />
    <%
    // Connect to the LDAP server.
    Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port + "/");

    // Search and retrieve DN.
    try {
        LdapContext ldap = new InitialLdapContext(env, null);
        NamingEnumeration results = ldap.search(basedn, filter, null);
        String binddn = "None";
        while (results.hasMore()) {
            SearchResult sr = (SearchResult) results.next();
            binddn = sr.getName() + "," + basedn;
        }
    %>
    <p>Bind DN found: <%= binddn%><hr /></p>
    <%
        ldap.close();

        // Authenticate
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, binddn);
        env.put(Context.SECURITY_CREDENTIALS, password);

        ldap = new InitialLdapContext(env, null);
    %>
    <p>Successful authentication for <%= user%>.</p>

This is my LDAP server details

I get the below exception which I dont really understand and I have tried many suggestions but nothing fruitful. Could anyone please help me fix this, it would help me proceed with building up my app based on this. Please also give your suggestions on authentication with Active Directory LDAP in Tomcat.

Sep 17, 2013 1:40:32 PM org.apache.catalina.realm.JNDIRealm authenticate SEVERE: Exception performing authentication javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C09062B, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, va28

1
This is a binding issue, it could be for multiple reasons ,bad username or password, wrong authentication type ... etc check below how to connect and query ADSaddam Abu Ghaida

1 Answers

0
votes

Note: the filter you used UID while this attribute is not supported nativly in AD

second check below code to be able to connect the right way

package lib;


/**
 * @author sghaida
 *
 */


import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.security.cert.CertificateException;

import ccc.gr.moa.server.FTPMIServiceImpl;

import com.extjs.gxt.ui.client.data.BaseModel;

public class ADConnector {

    /**
     * @param args
     */

    @SuppressWarnings("unchecked")
    static  Hashtable<String, String> envGC = new Hashtable();

    static String adminName;
    static String adminPassword;
    static String urlGC;
    static String searchBase;

    static LdapContext ctxGC;


    public ADConnector() throws NamingException
    {

        //get AD properties
        urlGC = "ldap://" + FTPMIServiceImpl.ADProperties.get("ADHostname")+ ":3268";
        adminName = FTPMIServiceImpl.ADProperties.get("bindDN");
        adminPassword = FTPMIServiceImpl.ADProperties.get("bindPassword");
        searchBase = FTPMIServiceImpl.ADProperties.get("searchBase");


        envGC.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
        //envDC.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

        //set security credentials, note using simple cleartext authentication
        envGC.put(Context.SECURITY_AUTHENTICATION,"simple");
        envGC.put("java.naming.ldap.attributes.binary","userCertificate");
        envGC.put(Context.SECURITY_PRINCIPAL,adminName);
        envGC.put(Context.SECURITY_CREDENTIALS,adminPassword);

        //envDC.put(Context.SECURITY_AUTHENTICATION,"simple");
        //envDC.put(Context.SECURITY_PRINCIPAL,adminName);
        //envDC.put(Context.SECURITY_CREDENTIALS,adminPassword);

        //connect to both a GC and  DC
        envGC.put(Context.PROVIDER_URL,urlGC);
        //envDC.put(Context.PROVIDER_URL,urlDC);
        //Create the initial directory context for both DC and GC
        ctxGC = new InitialLdapContext(envGC,null);
        //ctxDC = new InitialLdapContext(envDC,null);
    }

    /**
     * @param name
     * @return
     * @throws NamingException
     */
    /**
     * @param name
     * @return
     * @throws NamingException
     */
    public List<BaseModel> searchResults(String searchFilter ) throws NamingException
    {
        //Create the search controls        
        SearchControls searchCtls = new SearchControls();

        //Specify the attributes to return
        //String returnedAtts[]={"sn","givenName","mail","userCertificate"};
        String returnedAtts[]={"cn","sn","givenName","sAMAccountName","mail","distinguishedName"};
        searchCtls.setReturningAttributes(returnedAtts);


        //Specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        //Specify the Base for the search
        //String searchBase = "dc=ccg,dc=local";

        //initialize counter to total the results
        int totalResults = 0;

        //Search for objects in the GC using the filter
        NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);

        List<BaseModel> results = new ArrayList<BaseModel>();

        while (answer.hasMoreElements()) {

            SearchResult sr = (SearchResult)answer.next(); 
            totalResults++;

            // Print out some of the attributes, catch the exception if the attributes have no values

            Attributes attrs = sr.getAttributes();
            if (attrs != null) {
                try {

                    System.out.println("   cn(GC): " + attrs.get("cn").get());
                    System.out.println("   sn(GC): " + attrs.get("sn").get());
                    System.out.println("   givenName(GC): " + attrs.get("givenName").get());
                    System.out.println("   mail(GC): " + attrs.get("mail").get());
                    System.out.println("   sAMAccountName(GC): " + attrs.get("sAMAccountName").get());
                    System.out.println("   distinguishedName(GC): " + attrs.get("distinguishedName").get());

                    BaseModel bm = new BaseModel();

                    bm.set("full_name", attrs.get("cn").get());
                    bm.set("last_name", attrs.get("sn").get());
                    bm.set("first_name", attrs.get("givenName").get());

                    bm.set("email",attrs.get("mail").get());
                    bm.set("account_name", attrs.get("sAMAccountName").get());

                    results.add(bm);

                }
                catch (NullPointerException e)  {
                    System.err.println("Problem listing attributes from Global Catalog: " + e);
                    e.printStackTrace();
                }

            }

        }
        ctxGC.close();
        return results;

    }


    public static void main(String[] args) throws CertificateException, NamingException {

        ADConnector connector = new ADConnector();
        //specify the LDAP search filter
        String searchFilter = "(sAMAccountName=sghaida)";
        List<BaseModel> results = connector.searchResults(searchFilter);


    }

}