LDAP은 시스템의 사용자의 계정 이름, 암호, 주소, 전화 번호 등등 시스템 사용자의 정보를 담고 있는 저장소 이다. 그리고, 자바에서 이런 LDAP 서버에 접근해서 사용자 정보를 찾으려는 경우가 있다. 그 때 필요한 내용을 정리해 둔다.
자바에서 LDAP 서버에 접근을 해서 정보를 가져오려면 가장 먼저 인증서를 가지고 있어야 한다. 그래서 다음의 자바 파일을 컴파일하고 실행한다.
- 파일을 실행하면, jssecacerts 라는 파일이 사용자 home 폴더에 생성될 것이다.
- jssecacerts 파일을 $JAVA_HOME/jre/lib/security에 복사한다.
이제 LDAP 서버에 연결할 준비는 모두 완료되었다. 이제 다음과 같이 테스트 해볼 수 있다.
package myutil;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.apache.commons.beanutils.PropertyUtils;
import de.mpg.tuebingen.shore.util.model.Member;
public class LDAPConnection {
private static final String SEARCH_BASE = "ou=users,dc=firstdomain,dc=co,dc=kr";
private LdapContext ctxForUseInformation;
private LdapContext ctxForLogin;
private Hashtable<String, String> env;
public static void main(String[] args) {
LDAPConnection con = new LDAPConnection();
try {
con.testSearchBy();
} catch (NamingException e) {
e.printStackTrace();
}
}
public void testSearchBy() throws NamingException {
TreeSet<String> attributeNames = new TreeSet<>();
NamingEnumeration<SearchResult> results = searchBy("uid", "*");
while (results != null && results.hasMore()) {
SearchResult sr = results.next();
String dn = sr.getName() + "," + getSearchBase();
Attributes ar = getAttributes(dn);
if (ar == null)
return;
NamingEnumeration<? extends Attribute> attrs = ar.getAll();
while (attrs.hasMoreElements()) {
Attribute attr = attrs.nextElement();
// if(!"uid".equals(attr.getID())) continue;
System.out.print(attr.getID() + ":");
attributeNames.add(attr.getID());
for (NamingEnumeration<?> vals = attr.getAll(); vals
.hasMoreElements();) {
System.out.println("\t" + vals.nextElement());
}
System.out.println();
}
}
System.out.println(attributeNames);
}
public LDAPConnection() {
env = new Hashtable<>(11);
// Must use the name of the server that is found in its certificate
env.put(Context.PROVIDER_URL, "ldaps://ldap.localnet/");
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
try {
ctxForUseInformation = new InitialLdapContext(env, null);
ctxForUseInformation.addToEnvironment(
Context.SECURITY_AUTHENTICATION, "simple");
ctxForUseInformation.addToEnvironment(Context.SECURITY_PRINCIPAL,
"cn=jbosskruecke,dc=tuebingen,dc=mpg,dc=de");
ctxForUseInformation.addToEnvironment(Context.SECURITY_PROTOCOL,
"ssl");
ctxForUseInformation.addToEnvironment(Context.SECURITY_CREDENTIALS,
"cysBuel7");
} catch (NamingException e) {
e.printStackTrace();
}
}
public NamingEnumeration<SearchResult> searchBy(String criteria,
String value) {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
try {
return ctxForUseInformation.search(SEARCH_BASE,
String.format("%s=%s", criteria, value), constraints);
} catch (NamingException e) {
e.printStackTrace();
}
return null;
}
public String getSearchBase() {
return SEARCH_BASE;
}
public Attributes getAttributes(String dn) {
try {
return ctxForUseInformation.getAttributes(dn);
} catch (NamingException e) {
e.printStackTrace();
}
return null;
}
public boolean login(String id, String pw) {
try {
ctxForLogin = new InitialLdapContext(env, null);
ctxForLogin.addToEnvironment(Context.SECURITY_AUTHENTICATION,
"simple");
ctxForLogin.addToEnvironment(Context.SECURITY_PROTOCOL, "ssl");
ctxForLogin
.addToEnvironment(
Context.SECURITY_PRINCIPAL,
String.format(
"uid=%s,ou=abt6,ou=eb,ou=users,dc=tuebingen,dc=mpg,dc=de",
id));
ctxForLogin.addToEnvironment(Context.SECURITY_CREDENTIALS, pw);
ctxForLogin.reconnect(ctxForLogin.getRequestControls());
} catch (Exception e) {
System.out.println(e);
return false;
}
return true;
}
public void close() {
try {
ctxForLogin.close();
ctxForUseInformation.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
public Set<String> searchAllAttributes() {
TreeSet<String> attributes = new TreeSet<String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results;
try {
results = ctxForUseInformation.search(SEARCH_BASE, "uid=*", constraints);
while (results != null && results.hasMore()) {
SearchResult sr = results.next();
String distinguishedName = sr.getName() + "," + SEARCH_BASE;
Attributes ar = ctxForUseInformation.getAttributes(distinguishedName);
if (ar == null)
return attributes;
NamingEnumeration<? extends Attribute> attrs = ar.getAll();
while (attrs.hasMoreElements()) {
Attribute attr = attrs.nextElement();
attributes.add(attr.getID());
for (NamingEnumeration<?> vals = attr.getAll(); vals
.hasMoreElements();) {
vals.nextElement();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return attributes;
}
public Set<Member> searchAllMembers() {
TreeSet<Member> members = new TreeSet<Member>();
HashSet<Map<String, String>> maps = new HashSet<Map<String, String>>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results;
try {
results = ctxForUseInformation.search(SEARCH_BASE, "uid=*", constraints);
while (results != null && results.hasMore()) {
SearchResult sr = results.next();
String distinguishedName = sr.getName() + "," + SEARCH_BASE;
Attributes ar = ctxForUseInformation.getAttributes(distinguishedName);
if (ar == null)
return members;
HashMap<String, String> map = new HashMap<String, String>();
NamingEnumeration<? extends Attribute> attrs = ar.getAll();
while (attrs.hasMoreElements()) {
StringBuffer infoBuffer = new StringBuffer();
Attribute attr = attrs.nextElement();
for (NamingEnumeration<?> vals = attr.getAll(); vals.hasMoreElements();) {
infoBuffer.append(vals.nextElement()).append(",");
}
infoBuffer.setLength(infoBuffer.length() - 1);
map.put(attr.getID(), infoBuffer.toString());
}
maps.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
for(Map<String, String> map : maps) {
Member member = new Member();
for(String key : map.keySet()) {
String realKey = Member.getKey(key);
String value = map.get(key);
try {
PropertyUtils.setProperty(member, realKey, value);
} catch (Exception e) {
e.printStackTrace();
}
}
members.add(member);
}
return members;
}
}
이런 식으로 실행해 볼 수 있을 것이다.
댓글