發表於 程式分享

java-透過ldap登入公司AD Server

透過ldap登入公司AD Server ,我將程式包成函數

   public boolean LDAP_AUTH_AD(String ldap_url, String sLdapdc,String username, String password) {     
        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, sLdapdc + "\\" + username);
        env.put(Context.SECURITY_CREDENTIALS, password);

        LdapContext ctx = null;
        try {
            ctx = new InitialLdapContext(env, null);
        } catch (javax.naming.AuthenticationException e) {
            this.setMessage("登入失敗- [員工編號] 或 [AD密碼] 輸入錯誤 !");
            logger.warn(username + ":登入失敗- [員工編號] 或 [AD密碼] 輸入錯誤 ! => " + e.getMessage());
            return false;
        } catch (javax.naming.CommunicationException e) {
            this.setMessage("登入失敗- 找不到認證主機 !");
            logger.error(username + ":登入失敗- 找入到認證主機 ! => " + e.getMessage());
            return false;
        } catch (Exception e) {         
            this.setMessage("登入失敗- 發生未知的錯誤,請洽系統管理員 !");
            logger.error(username + ":登入失敗- 發生未知的錯誤,請洽系統管理員 ! => " + e.getMessage());
            return false;
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(username + ":ctx.close()發生錯誤 ! => " + e.getMessage());
                } 
            }
        }   
        return true;
    }

ldap_url: 格式如ldap://localhost:389/
sLdapdc: 格式如cn=S. User, ou=NewHires, o=JNDITutorial
username: AD帳號
password: AD密碼

發表留言