Server Fault
Server Fault

Reputation: 637

How can I find an LDAP user's DN in JSP?

I am trying to find a user's OU within an LDAP tree in JSP. I can retrieve many of the user's LDAP attributes with the following code:

Hashtable<String, String> tenv = new Hashtable<String, String>();

tenv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
tenv.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:389/");

SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);   

LdapContext lctx = new InitialLdapContext(tenv, null);
String filter = "cn=" + userid;
NamingEnumeration res = lctx.search ("dc=my,dc=dom,dc=org", filter, sc);

while (res.hasMore()) 
{
   SearchResult s = (SearchResult) res.next();
   Attributes attrs = s.getAttributes();
   Attribute attr = attrs.get("SN");
   out.println ("<font color=red>" + attr + "</font>");
}

When I run ldapsearch at the Linux command line, with similar search parameters, I can see a DN: which shows the OU the user is in (dn: uid=username,ou=users,dc=my,dc=dom,dc=org). I've tried attrs.get("DN") and was returned null. How can I retrieve this DN: in JSP?

Upvotes: 2

Views: 3498

Answers (1)

Server Fault
Server Fault

Reputation: 637

Apparently there is "there is no direct way of obtaining the Distinguished Name (DN) from the search results."

This code will do it:

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.ldap.*;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
class GetAllAttrs 
{

  public static void main(String[] args) 
  {
    String filter = "cn=myuser";    // this is the user to look for
    String baseDN = "dc=my,dc=dom,dc=org";
    String ldapURL = "ldap://192.168.101.1:389";

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapURL);

    try 
    {
      // Create the initial context
      LdapContext ctx = new InitialLdapContext(env, null);

      SearchControls sc = new SearchControls();
      sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
      NamingEnumeration res = ctx.search (baseDN, filter, sc);

      while (res.hasMore()) 
      {
         SearchResult s = (SearchResult) res.next();

         // print user's DN
         System.out.println(">>" + s.getNameInNamespace());
      }

      // Close the context when we're done
      ctx.close();

    } 
    catch (Exception e) 
    {
      e.printStackTrace();
    }
  }
}

Upvotes: 6

Related Questions