上文講到如何利用Java 去接駁LDAP, 今次則利用Spring security 作示範. 比較之下Spring 簡化了連接過程.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.EqualsFilter;
public static void totalUser() throws NamingException
{
try {
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl("ldap://localhost:10389");
ctxSrc.setBase("dc=ldap,dc=sample,dc=local");
ctxSrc.setUserDn("uid=admin,ou=system");
ctxSrc.setPassword("secret");
ctxSrc.afterPropertiesSet();
LdapTemplate tmpl = new LdapTemplate(ctxSrc);
EqualsFilter filter = new EqualsFilter("objectclass", "inetOrgPerson");
List<Object> result= tmpl.search(DistinguishedName.EMPTY_PATH,
filter.encode(),
new AttributesMapper<Object>() {
public Object mapFromAttributes(Attributes attrs) throws NamingException, javax.naming.NamingException {
return attrs.get("cn").get();
}
});
for(Object user: result) {
System.out.println(user);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Leave a Reply