如何使用 Java 连接到 Active Directory [英] How to connect with Java into Active Directory
本文介绍了如何使用 Java 连接到 Active Directory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 Weblogic,Ejb3.0.Java 1.6
I am using Weblogic, Ejb3.0. Java 1.6
我需要通过 Java 代码访问 Active Directory.我阅读了几种方式(Kerberos、LDAP)
I need to access Active Directory via Java code. I read about several ways (Kerberos, LDAP)
任何人都可以建议我以舒适的方式这样做吗?我在哪里可以找到一些完整的代码示例,
Anyone could advice me on comfortable way of doing so? where could I have some full code examples,
谢谢,雷.
推荐答案
这是一个简单的代码,用于在 W2K3 上使用 JNDI 进行身份验证和进行 LDAP 搜索:
Here is a simple code that authenticate and make an LDAP search usin JNDI on a W2K3 :
class TestAD
{
static DirContext ldapContext;
public static void main (String[] args) throws NamingException
{
try
{
System.out.println("Début du test Active Directory");
Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//ldapEnv.put(Context.PROVIDER_URL, "ldap://societe.fr:389");
ldapEnv.put(Context.PROVIDER_URL, "ldap://dom.fr:389");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
//ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
//ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
//ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
ldapContext = new InitialDirContext(ldapEnv);
// Create the search controls
SearchControls searchCtls = new SearchControls();
//Specify the attributes to return
String returnedAtts[]={"sn","givenName", "samAccountName"};
searchCtls.setReturningAttributes(returnedAtts);
//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//specify the LDAP search filter
String searchFilter = "(&(objectClass=user))";
//Specify the Base for the search
String searchBase = "dc=dom,dc=fr";
//initialize counter to total the results
int totalResults = 0;
// Search for objects using the filter
NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);
//Loop through the search results
while (answer.hasMoreElements())
{
SearchResult sr = (SearchResult)answer.next();
totalResults++;
System.out.println(">>>" + sr.getName());
Attributes attrs = sr.getAttributes();
System.out.println(">>>>>>" + attrs.get("samAccountName"));
}
System.out.println("Total results: " + totalResults);
ldapContext.close();
}
catch (Exception e)
{
System.out.println(" Search error: " + e);
e.printStackTrace();
System.exit(-1);
}
}
}
这篇关于如何使用 Java 连接到 Active Directory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文