1

I've been attempting to build a web app running on Tomcat 9 which authenticates users via an LDAP server. Please see my code below:

        String username = request.getParameter("uname");
        String password = request.getParameter("password");
        
        String base = "DC=xsoltns,DC=y";
        String dn = "CN=Admin,CN=Users," + base;
        String ldap_url = "ldap://address:389";
        
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, ("com.sun.jndi.ldap.LdapCtxFactory"));
        props.put(Context.PROVIDER_URL, ldap_url);
        props.put(Context.SECURITY_PRINCIPAL, dn);
        props.put(Context.SECURITY_CREDENTIALS, "adminpassword");
        
        try 
        {
            InitialDirContext context = new InitialDirContext(props);
            
            String principle_name = username+"@mydomain.com";
            
            
            SearchControls ctrls = new SearchControls();
            ctrls.setReturningAttributes(new String[] {"givenName", "sn", "memberOf"});
            ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            
            NamingEnumeration<javax.naming.directory.SearchResult> answers = 
                    context.search(base, "(uid="+principle_name+")", ctrls);
            javax.naming.directory.SearchResult result = answers.nextElement();
            String user = result.getNameInNamespace();
            
            try 
            {
                props = new Properties();
                props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                props.put(Context.PROVIDER_URL, ldap_url);
                props.put(Context.SECURITY_PRINCIPAL, user);
                props.put(Context.SECURITY_CREDENTIALS, password);

                context = new InitialDirContext(props);
                
                //user authenticated
                
            } catch (Exception e)
            {
                //error with user auth
            }
                    
            
        } catch (Exception e) 
        {
            //error with admin auth
            
        }

The program successfully binds using the Admin account, but the user isn't being located based on their provided username. I've been using a previous answer LDAP Authentication using Java for reference when building this application. My goal here is to provide the username and then search the directory for the user's full name (to provide as the CN for the secondary authentication). After some testing, I've found that user and answers are returning null, i.e. no user is found. I don't quite understand why this is happening, is there something else I need to provide for the search? What should I do?

HotPupper
  • 11
  • 1

0 Answers0