搜索中關於java 登錄ldap,大部分會采用 cn=xxx,ou=xxx,dc=xxx的方式,此處的cn是用戶的Display Name,而不是account,而且如果ou有多層,比如我們的OU就會超過三層。
那最好是通過用戶的account直接登錄
代碼如下:
/** * 獲取默認LDAP連接
* Exception 則登錄失敗,ctx不為空則登錄成功 * @return void */ public static LdapContext getLDAPConnection() throws AuthenticationException, CommunicationException,Exception { LdapContext ctx = null; //LDAP 連接地址 ldap://IP:PORT (default port 389) String LDAP_URL = ""; //LDAP SSL連接地址 ldaps://IP:PORT (default port 636) //(這個用起來比較麻煩,目前知道管理員改密碼必須使用SSL) String LDAP_SSL_URL = ""; //用戶名 String userAccount = ""; //管理員密碼 String userPassword = ""; // 方式1 // 基於姓名(cn),此cn為Display Name,部門有同名就麻煩了 userAccount = "cn=xxx,OU=xxx,DC=xxx,DC=com"; // 方式2 // 基於Account User Logon name: // userAccount = "xxx@domain.xxx"; // 方式3 // 基於Account User Logon name(pre-windows 2000): // userAccount = "domain\\xxx" // 基於登錄名(uid (User ID)與 unix 的 uid 完全不同)(請注意objectSID,此處嘗試失敗) // uid=abc123, ou=xxxx, dc=xxxx, dc=com userPassword = "xxxxx"; Hashtable<String,String> HashEnv = new Hashtable<String,String>(); HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP訪問安全級別(none,simple,strong) HashEnv.put(Context.SECURITY_PRINCIPAL, userAccount); //AD的用戶名 HashEnv.put(Context.SECURITY_CREDENTIALS, userPassword); //AD的密碼 HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工廠類 HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//連接超時設置為3秒 HashEnv.put(Context.PROVIDER_URL, LDAP_URL); ctx = new InitialLdapContext(HashEnv, null);//new InitialDirContext(HashEnv);// 初始化上下文 return ctx; }