2016年3月8日 星期二

JAVA junit測試 AD帳密驗證 + search AD displayName(顯示名稱)

package junit.test.AD;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.junit.Test;


public class AdTest {
 @Test
 public void test() {
//  ResourceBundle res = ResourceBundle.getBundle("config");
//  String ldapURL = res.getString("Active.directory.ldapURL");
  String ldapURL = "ldap://172.23.101.108:389" ;
  System.out.println(ldapURL);
  String account = "admin";
  String password = "p@ssw0rd";
  try{
     LDAP_AUTH_AD(ldapURL, account, password);
   System.out.println("認證成功!");
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
 }
 public static void LDAP_AUTH_AD(String ldap_url, String account, String password) throws Exception {
     if (account.isEmpty() || password.isEmpty()) throw new Exception("認證失敗!");
        Hashtable env = new Hashtable();
        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+"@mizuho.com");
        env.put(Context.SECURITY_CREDENTIALS, password);

        LdapContext ctx = null;
        try {
            ctx = new InitialLdapContext(env, null);
        } catch (AuthenticationException e) {
         /**
         * error Code 說明 : 
         * 525 : 用戶沒有找到
         * 52e : 證號不正確
         * 530 : 此時間不允許登入(not permitted to logon at this time)
         * 532 : 密碼期滿
         * 533 : 帳號不可用
         * 701 : 帳戶期滿
         * 773 : 用戶必須重設密碼
         * data 後面為錯誤代碼
         */
         throw new Exception(e.getMessage() + "認證失敗!");
        } catch (CommunicationException e) {
         throw new Exception("找不到伺服器!");
        } catch (Exception e) {
         throw new Exception("發生未知的錯誤!");
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                }
            }
        }      
    }
 @Test
 public void testQueryAdUser() throws NamingException {
  String userId = "admin" ;
  String ldapURL = "ldap://172.23.101.108:389" ;
  String domainName = "mizuho.com";
  String account = "admin";
  String password = "p@ssw0rd";
  
  Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapURL);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, account+"@"+domainName);
        env.put(Context.SECURITY_CREDENTIALS, password);
        
        LdapContext ldapContext = new InitialLdapContext(env, null);
  
  SearchControls searchCtls = new SearchControls();
  String returnedAtts[] = { "sn", "givenName", "samAccountName","displayName" };
  
  searchCtls.setReturningAttributes(returnedAtts);
  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  String searchFilter = "(&(userPrincipalName="+userId+"@"+domainName+"))";
  String searchBase = "dc=mizuho,dc=com";
  
  // initialize counter to total the results
  int totalResults = 0;

  // Search for objects using the filter
  NamingEnumeration 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());
   String displayName = sr.getName().replace("CN=", "");
   displayName = displayName.split(",")[0] ;
   System.out.println("displayName >>" + displayName);
   Attributes attrs = sr.getAttributes();
   System.out.println(">>>>>>" + attrs.get("samAccountName"));
  }
  System.out.println("Total results: " + totalResults);
  ldapContext.close();
 }
}

沒有留言:

張貼留言