環境:
OS : Windows Server 2k3
Domain: mydomain.com
Host : x.x.x.x(此為指定 ip address)
以 Java 程式撰寫 對 LDAP-AD 的認證, 程式碼如下:
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
/**
* AD LDAP 登入認證
*
* @param ldap_url like ldap://x.x.x.x:389/DC=mydomain,DC=com
* @param account
* @param password
* @return String[0] array 0 :0 success,1 fail,2 LDAP connect fail,3 unknow
*/
public String[] LDAP_AUTH_AD(String ldap_url, String account, String password) {
String[] returnStr = new String[2];
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldap_url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, account+"@mydomain.com");
env.put(Context.SECURITY_CREDENTIALS, password);
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
returnStr[0] = "0";
} catch (javax.naming.AuthenticationException e) {
returnStr[0] = "1";
return returnStr;
} catch (javax.naming.CommunicationException e) {
// System.out.println("Can't connect to ldap server!");
returnStr[0] = "2";
return returnStr;
} catch (Exception e) {
System.out.println("error");
e.printStackTrace();
returnStr[0] = "3";
return returnStr;
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
}
}
}
}
沒有留言:
張貼留言