[Spring] 利用Spring security 去接駁LDAP

上文講到如何利用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();
		}
	}

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.