Java LDAP APIs

习惯了Perl里Net::LDAP,对于Java众多LDAP API甚为惊讶,这次TMTOWTDI (Tim Today)算是倒过来了。

闲话少说,Java客户端操作LDAP有以下可用方案:

 

  1. JNDI (自JDK 5以后内置)
  2. Apache Directory Client API
  3. jLDAP
  4. ldapSDK
  5. UnboundID API
  6. Spring LDAP

 JNDI用的比较多,不过使用起来很不方便。如果编写对LDAP数据修改的应用,用JNDI不是最佳选择。如果你用到了Spring 那么Spring LDAP是很自然的选择。

最后,附一段用JNDI进行密码验证的示例代码:

 

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
 
/**
 * Demonstrates how to authenticate user against QAD's LDAP server
 */
 
class Simple {
    public static void main(String[] args) {
    	Hashtable<String, String> authEnv = new Hashtable<String, String>(11);
    	String userName = "<your_login_here>";
    	String passWord = "<your_password_here>";
                  //TODO: change base DN to adpat to your LDAP directory structure
    	String base = "ou=Users,ou=Accounts,dc=example,dc=com";
    	String dn = "CN=" + userName + "," + base;
    	String ldapURL = "ldap://directory.example.com:389";
 
    	authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
   		authEnv.put(Context.PROVIDER_URL, ldapURL);
   		authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
   		authEnv.put(Context.SECURITY_PRINCIPAL, dn);
   		authEnv.put(Context.SECURITY_CREDENTIALS, passWord);
 
    	try {
    		DirContext authContext = new InitialDirContext(authEnv);
    		System.out.println("Authentication Success!");
    	} catch (AuthenticationException authEx) {
    		System.out.println("Authentication failed!");
 
    	} catch (NamingException namEx) {
    		System.out.println("Something went wrong!");
    		namEx.printStackTrace();
    	}
    }
}
 
 

 

你可能感兴趣的:(java,spring,jdk,Security,perl)