java 調用ActiveDirectory,使用標準的LDAP協議

在ActiveDirectory中 支持 LDAP 協議,我們可以在 Java 中使用標準的 Java JNDI API 來訪問它。LDAP 服務器並非真的必須支持 JNDI API,只要支持 LDAP 協議就可以了。我們已經提供了一個簡單的測試案例程序來認證一個 LDAP 服務器的識別名。一般情況下,對待 ActiveDirectory 不必與對待任何其他的 LDAP 服務器有什麼不同。


import java.util.Properties;
import javax.naming.*;   
import javax.naming.directory.*;

//include the JNDI in the classpath. You should use the same JDK used by WebSphere Application server.

class wasLdapAuth 
{
public static void main(String[] args) 
{
    //***************** user information to be authenticated ********************************
    //*****************Please modify the following three properties accordingly ************
    String ldapHost= "ldap://cliang1.austin.ibm.com:389"; //ldap host + port number
    String DN = "cn=user1, ou=Austin,o=ibm,c=us";   // DN to be authenticated 
    String password = "security";  //  DN's password     
    //***************** End of user information
    
    Properties props = new Properties();  
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");    
 //for websphere 4.0 and 5.0
    //props.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.jndi.LDAPCtxFactory");     
 // for WebSphere 3.5 release 
    props.put(Context.SECURITY_AUTHENTICATION, "simple");     //use simple authentication mechanism
    props.put(Context.SECURITY_CREDENTIALS, password);  
    props.put(Context.SECURITY_PRINCIPAL, DN);     
    props.put(Context.PROVIDER_URL, ldapHost);  

    long start = System.currentTimeMillis();
    long end=0;
    long time =0;

    try 
        {
        System.out.println("authenticating");  
        DirContext ctx = new InitialDirContext(props);
        System.out.println("authenticated"); 
        end = System.currentTimeMillis();
        time = end - start;
        System.out.println( "authentication takes = " + time + " millis");     
        System.out.println("successfully authenticate DN: "+DN);

    } 
        catch (Exception ex)
    {
        end = System.currentTimeMillis();
        time = end - start;
        System.out.println("Exception is "+ex.toString()); 
        ex.printStackTrace();
        System.out.println( "authentication takes = " + time + " millis");    
        System.out.println("fail to authenticate DN: "+DN);
    }
}
}

    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章