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

Ser*_*ult 2 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>");
}
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*ult 6

显然,“没有直接的方法可以从搜索结果中获取专有名称 (DN)。 ”

这段代码会做到:

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)