Java透過LDAP驗證Windows AD

最近剛好寫到有關SSO(Single-SignOn)的功能,剛好後端又是用Java寫的,所以就用Java寫了一個跟AD(Active Directory)溝通的程式,用的是JNDI的API。

Java JNDI : http://docs.oracle.com/javase/tutorial/jndi/overview/




import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class ADtest {

public static void main(String[] args)
{
String ldapURL = "ldap://192.168.1.1:389";
String account = "test";
String password = "123456";
try{
  LDAP_AUTH_AD(ldapURL, account, password);
System.out.println("VerifySuccess!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}


public static void LDAP_AUTH_AD(String ldap_url, String account, String password) throws Exception {
    if (account.isEmpty() || password.isEmpty())
    throw new Exception("Username or Password is empty!");
   
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        //傳入AD Server位置
        env.put(Context.PROVIDER_URL, ldap_url);
        //可以設定三種參數(none, simple, strong)
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        //傳入帳號並冠上Domain
        env.put(Context.SECURITY_PRINCIPAL, account + "@testad.com");
        //密碼
        env.put(Context.SECURITY_CREDENTIALS, password);

        LdapContext ctx = null;
        try {
            ctx = new InitialLdapContext(env, null);
        } catch (javax.naming.AuthenticationException e) {
        throw new Exception("VerifyFail!");
        } catch (javax.naming.CommunicationException e) {
        throw new Exception("Can'tFindServer!");
        } catch (Exception e) {
        throw new Exception("OtherError!");
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                }
            }
        }      
    }
}



留言

這個網誌中的熱門文章

別再煩惱Linux手動分割磁碟了!!

Windows 防火牆 通過rtmp串流服務