项目需要LDAP验证,之前没有接触过,从网上查找代码,受益颇多,将代码记下,以便以后使用

  1. package com.test.ldap;    
  2.    
  3. import java.util.Hashtable;    
  4.    
  5. import javax.naming.AuthenticationException;    
  6. import javax.naming.Context;    
  7. import javax.naming.NamingEnumeration;    
  8. import javax.naming.NamingException;    
  9. import javax.naming.directory.DirContext;    
  10. import javax.naming.directory.SearchControls;    
  11. import javax.naming.directory.SearchResult;    
  12. import javax.naming.ldap.Control;    
  13. import javax.naming.ldap.InitialLdapContext;    
  14. import javax.naming.ldap.LdapContext;    
  15.    
  16.    
  17.    
  18. public class UserAuthenticate {    
  19.     private String URL = "ldap://localhost:389/";    
  20.     private String BASEDN = "ou=catalogue,o=test.com";    
  21.     private String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";    
  22.     private LdapContext ctx = null;    
  23.     private Hashtable env = null;    
  24.     private Control[] connCtls = null;    
  25.        
  26.        
  27.     private void LDAP_connect(){    
  28.         env = new Hashtable();    
  29.         env.put(Context.INITIAL_CONTEXT_FACTORY,FACTORY);    
  30.         env.put(Context.PROVIDER_URL, URL+BASEDN);//LDAP server    
  31.         env.put(Context.SECURITY_AUTHENTICATION, "simple");    
  32. //此处若不指定用户名和密码,则自动转换为匿名登录    
  33.            
  34.         try{    
  35.             ctx = new InitialLdapContext(env,connCtls);    
  36.         }catch(javax.naming.AuthenticationException e){    
  37.             System.out.println("Authentication faild: "+e.toString());    
  38.         }catch(Exception e){    
  39.             System.out.println("Something wrong while authenticating: "+e.toString());    
  40.         }    
  41.     }    
  42.        
  43.        
  44.     private String getUserDN(String email){    
  45.         String userDN = "";    
  46.            
  47.         LDAP_connect();    
  48.            
  49.         try{    
  50.                SearchControls constraints = new SearchControls();    
  51.                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);    
  52.                NamingEnumeration en = ctx.search("""mail="+email, constraints); //The UID you are going to query,* means all nodes    
  53.                if(en == null){    
  54.                 System.out.println("Have no NamingEnumeration.");    
  55.                }    
  56.                if(!en.hasMoreElements()){    
  57.                 System.out.println("Have no element.");    
  58.                }    
  59.                while (en != null && en.hasMoreElements()){//maybe more than one element    
  60.                    Object obj = en.nextElement();    
  61.                    if(obj instanceof SearchResult){    
  62.                        SearchResult si = (SearchResult) obj;    
  63.                        userDN += si.getName();    
  64.                        userDN += "," + BASEDN;    
  65.                    }    
  66.                    else{    
  67.                        System.out.println(obj);    
  68.                    }    
  69.                    System.out.println();    
  70.                }    
  71.               }catch(Exception e){    
  72.                System.out.println("Exception in search():"+e);    
  73.               }    
  74.            
  75.         return userDN;    
  76.     }    
  77.        
  78.        
  79.     public boolean authenricate(String ID,String password){    
  80.         boolean valide = false;    
  81.         String userDN = getUserDN(ID);    
  82.            
  83.         try {    
  84.             ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,userDN);    
  85.             ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,password);    
  86.             ctx.reconnect(connCtls);    
  87.             System.out.println(userDN + " is authenticated");    
  88.             valide = true;    
  89.         }catch (AuthenticationException e) {    
  90.             System.out.println(userDN + " is not authenticated");    
  91.             System.out.println(e.toString());    
  92.             valide = false;    
  93.         }catch (NamingException e) {    
  94.             System.out.println(userDN + " is not authenticated");    
  95.             valide = false;    
  96.         }    
  97.            
  98.         return valide;    
  99.     }    
  100. }