如何在JSP中找到LDAP用户的DN?

时间:2015-07-20 13:17:12

标签: java jsp openldap

我试图在JSP中的LDAP树中找到用户的OU。我可以使用以下代码检索许多用户的LDAP属性:

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>");
}

当我在Linux命令行运行ldapsearch时,使用类似的搜索参数,我可以看到一个DN:显示用户所在的OU( dn:uid = username,ou = users,dc = my, DC = DOM,DC =组织)。 我尝试过attrs.get(“DN”)并返回null。如何在JSP中检索此DN?

1 个答案:

答案 0 :(得分:3)

显然有“there is no direct way of obtaining the Distinguished Name (DN) from the search results.

此代码将执行此操作:

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();
    }
  }
}