출처 : http://evilimp.tistory.com/380

AD(ldap) 테스트용 Java 코드

어제 구글링을 하다가 SF에서 찾은 소스....

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
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;

public class AdTest {

 @SuppressWarnings("unchecked")
 public static void main(String[] args) throws Exception {

  String ntUserId = "검색하고자하는사용자ID";
  String ntPasswd = "검색하고자하는사용자비밀번호";
  String url = "ldap://ldap서버명";
  String domain = "LDAP도메인(대문자)"; // 회사명이 domain.com이라면 DOMAIN
  String searchBase = "DC=domain,DC=com"; // 검색대상 tree

  Hashtable env = new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, url);
  env.put(Context.SECURITY_AUTHENTICATION, "simple");
  env.put(Context.SECURITY_PRINCIPAL, domain + "\\" + ntUserId);
  env.put(Context.SECURITY_CREDENTIALS, ntPasswd);

  LdapContext ctx = new InitialLdapContext(env, null);
  SearchControls sc = new SearchControls();
  sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
  sc.setReturningAttributes(new String[] { "cn", "mail" });
  NamingEnumeration results = ctx.search(searchBase, "sAMAccountName=" + ntUserId, sc);
  while (results.hasMoreElements()) {
   SearchResult sr = (SearchResult) results.next();
   Attributes attrs = sr.getAttributes();
   System.out.println("attributes: " + attrs);
  }
 }
}

이녀석을 가지고 돌려보면 해당 사용자가 존재하고 비밀번호도 맞다면 등록된 mail 주소를 반환해준다.

+ Recent posts