您的位置:首页 > 编程语言 > Java开发

java 调用ActiveDirectory,使用标准的LDAP协议

2008-05-01 06:24 411 查看
在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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: