栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Java连接到Active Directory

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Java连接到Active Directory

这是一个简单的代码,用于在W2K3上的JNDI中进行身份验证并进行LDAP搜索:

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);    }  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507192.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号