Java 要對 Windows Server AD (Active Directory) 的認證整合,程式碼如下:
Step 01: 準備一個共用函數 LDAP_AUTH_AD
/** * AD LDAP 登入認證 * * @param ldap_url * like ldap://912.168.2.1:389/DC=WEI,DC=COM * @param account * @param password * @return String[2] array 0 :0 success,1 fail,2 LDAP connect fail,3 unknow * error array 1 :useremail */ 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); env.put(Context.SECURITY_CREDENTIALS, password); LdapContext ctx = null; try { ctx = new InitialLdapContext(env, null); returnStr[0] = "0"; SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(sAMAccountName=" + account + ")"; String searchBase = ""; int totalResults = 0; String returnedAtts[] = { "mail" }; searchCtls.setReturningAttributes(returnedAtts); try { NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes Attrs = sr.getAttributes(); if (Attrs != null) { try { for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore();) { Attribute Attr = (Attribute) ne.next(); for (NamingEnumeration e = Attr.getAll(); e.hasMore(); totalResults++) { returnStr[1] = e.next().toString(); } } } catch (NamingException e) { System.err.println("Throw Exception : " + e); } } } loger.debug("Number: " + totalResults); } catch (Exception e) { loger.error("Can't find Email Address"); } return returnStr; } catch (javax.naming.AuthenticationException e) { returnStr[0] = "1"; e.printStackTrace(); 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) { } } } } |
Step 02: 主程式
// 取得認證URL String LDAP_URL="ldap://192.168.2.1:389/DC=WEI,DC=COM;WEI.COM"; LDAP_URL = LDAP_URL.split(";")[0];; // 取得該公司網域 String AD_Domain=""; AD_Domain = "@"+LDAP_URL.split(";")[1].trim(); // AD認證方式登入 if(AUTH_METHOD.equalsIgnoreCase("AD") && !isLogin) { String[] as = baTools.LDAP_AUTH_AD(LDAP_URL, users.getUserName()+AD_Domain, users.getUserPassword()); if (as[0].equals("0")) { isLogin = true; loginResult= SUCCESS; }else{ this.addActionError("帳號登入錯誤"); } } // end AD認證方式登入 |
這樣就可以與您的公司的 AD (Active Directory) LDAP認證主機作整合.
程式碼:Java 對於LDAP: Windows Server AD (Active Directory) 的認證整合
http://misforum.ddns.net/forum.php?mod=viewthread&tid=20&fromuid=2
(出處: MISForum 資訊論壇)
文章標籤
全站熱搜
留言列表