This Blog instruction will help us to do LDAP programming using Spring framework LDAP api. This Blog instruction create simple example of search, create, read, update and delete (SCRUD) using Spring framework LDAP api.
Please note I am huge fan of ldap command line tool. First I learned ldap command line from Oracle ldap comtool.
After I read specification of Spring LDAP I found easy to work with. This blog instruction is simple spring ldap api example. Soon I will also publish another example of spring ldap api usage with spring ldap framework ODM api.
Pre-requsite
Instructions assume that jdk, Apache DS, Apache Directory Studio is installed without any error.
We have to start LDAP service. After installation of Apache DS following image will guide us to start default LDAP service.
We got check default Apache DS. After starting Apache DS following image will guide us to explore newly started LDAP services.
Implemenation instructions
-
Required Software
- Developemnt
- Testing
- Java test class used for testing.
- Create a Simple spring project name "spring-ldap-example". Following image will guide us. Add the required libraries in classpath. - spring-aop-4.1.3.RELEASE.jar - spring-beans-4.1.3.RELEASE.jar - spring-context-4.1.3.RELEASE.jar - spring-context-support-4.1.3.RELEASE.jar - spring-core-4.1.3.RELEASE.jar - spring-expression-4.1.3.RELEASE.jar - spring-ldap-core-2.0.2.RELEASE.jar - spring-ldap-core-tiger-2.0.2.RELEASE.jar - spring-ldap-ldif-batch-2.0.2.RELEASE.jar - spring-ldap-ldif-core-2.0.2.RELEASE.jar - spring-ldap-test-2.0.2.RELEASE.jar - log4j-1.2.14.jar - slf4j-jcl-1.7.5.jar
- Create folder name resource and add in classpath. Create test_data.ldif in resource folder and following snippet. This test_data.ldif is used to prepare test data.
- Create package ldap.advance.example
- Create simple pojo class User and following snippet.
- Create interface UserRepositoryIntf and add following snippet. We will define all following methods to implements example of SCRUD functions.
- Create class UserRepositoryImpl implements interface UserRepositoryIntf and add following snippet.
- Following table will explain the methods that used to SCRUD functionalities.
- Create class customize AttributesMapper name UserAttributesMapper and add following snippet.
- Create class customize AttributesMapper name SingleAttributesMapper and add following snippet.
- Create class customize AttributesMapper name MultipleAttributesMapper and add following snippet.
- Create spring bean configuration spring-ldap-example.xml in resource folder.
- Create log4j.xml in resource folder and add following snippet.
version: 1
dn: dc=example,dc=com
objectclass: top
objectclass: domain
dc: example
dn: ou=groups,dc=example,dc=com
objectClass: top
objectClass: organizationalUnit
ou: groups
description: this will contains all the groups
dn: uid=kaustuv,ou=users,dc=example,dc=com
objectClass: organizationalPerson
objectClass: person
objectClass: uidObject
objectClass: top
cn: kaustuv
sn: maji
uid: kaustuv
postalAddress: GC 207, Sector III, SaltlakeCity, Kolkata 700106, WestBengal, India
telephoneNumber: 9831198311
userPassword:: e1NTSEF9OXg3VGxzamNrQkFWZmVRRllRYnBXS25IUFYvV0hpdmtiSFNNMXc9PQ==
dn: cn=testGroup,ou=groups,dc=example,dc=com
objectClass: top
objectClass: groupOfUniqueNames
cn: testGroup
uniqueMember: uid=kaustuv,ou=users,dc=example,dc=com
o: kaustuv's blog
dn: ou=users,dc=example,dc=com
objectClass: top
objectClass: organizationalUnit
ou: users
dn: uid=guest,ou=users,dc=example,dc=com
objectClass: top
objectClass: uidObject
objectClass: person
objectClass: organizationalPerson
cn: guest
sn: guest
uid: guest
postalAddress: DreamLand
telephoneNumber: 9830098300
userPassword:: e1NTSEF9OXg3VGxzamNrQkFWZmVRRllRYnBXS25IUFYvV0hpdmtiSFNNMXc9PQ==
/**
*
* Copyright © Kaustuv Maji , 2014
* Repos - https://github.com/kaustuvmaji
* Blog - http://kaustuvmaji.blogspot.in
*
*/
package ldap.advance.example;
import java.io.Serializable;
/**
* @author KMaji
*
*/
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 9081527761576640803L;
private String uid;
private String cn;
private String sn;
private String userPassword;
private String postalAddress;
private String telephoneNumber;
/**
* @return the uid
*/
public synchronized final String getUid() {
return uid;
}
/**
* @param uid
* the uid to set
*/
public synchronized final void setUid(String uid) {
this.uid = uid;
}
/**
* @return the cn
*/
public synchronized final String getCn() {
return cn;
}
/**
* @param cn
* the cn to set
*/
public synchronized final void setCn(String cn) {
this.cn = cn;
}
/**
* @return the sn
*/
public synchronized final String getSn() {
return sn;
}
/**
* @param sn
* the sn to set
*/
public synchronized final void setSn(String sn) {
this.sn = sn;
}
/**
* @return the userPassword
*/
public synchronized final String getUserPassword() {
return userPassword;
}
/**
* @param userPassword
* the userPassword to set
*/
public synchronized final void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
/**
* @return the postalAddress
*/
public synchronized final String getPostalAddress() {
return postalAddress;
}
/**
* @param postalAddress
* the postalAddress to set
*/
public synchronized final void setPostalAddress(String postalAddress) {
this.postalAddress = postalAddress;
}
/**
* @return the telephoneNumber
*/
public synchronized final String getTelephoneNumber() {
return telephoneNumber;
}
/**
* @param telephoneNumber
* the telephoneNumber to set
*/
public synchronized final void setTelephoneNumber(String telephoneNumber) {
this.telephoneNumber = telephoneNumber;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [");
if (uid != null) {
builder.append("uid=");
builder.append(uid);
builder.append(", ");
}
if (cn != null) {
builder.append("cn=");
builder.append(cn);
builder.append(", ");
}
if (sn != null) {
builder.append("sn=");
builder.append(sn);
builder.append(", ");
}
if (userPassword != null) {
builder.append("userPassword=");
builder.append(userPassword);
builder.append(", ");
}
if (postalAddress != null) {
builder.append("postalAddress=");
builder.append(postalAddress);
builder.append(", ");
}
if (telephoneNumber != null) {
builder.append("telephoneNumber=");
builder.append(telephoneNumber);
}
builder.append("]");
return builder.toString();
}
}
/**
*
* Copyright © Kaustuv Maji , 2014
* Repos - https://github.com/kaustuvmaji
* Blog - http://kaustuvmaji.blogspot.in
*
*/
package ldap.advance.example;
import java.util.List;
/**
* <pre>
* This interface is used for
* a) fetch all the user details as a list of String
* b) fetch all the user details as a list of User object
* c) fetch user details of particular user.
* </pre>
*
* @author KMaji
*
*/
public interface UserRepositoryIntf {
/**
* This method is responsible to fetch all the user details as a list of
* String.
*
* @return list of String.
*/
public List<String> getAllUserNames();
/**
* This method is responsible to fetch all the user details as a list of
* User object
*
* @return list of {@link User}
*/
public List<User> getAllUsers();
/**
* This method is responsible to fetch user details of particular user.
*
* @return user details {@link User}
*/
public User getUserDetails(String userName);
/**
* This method is responsible to fetch user details of particular user as a string.
*
* @return user detail {@link User}
*/
public String getUserDetail(String userName);
/**
* This method is responsible to authenticate user.
*
* @return boolean true|false
*/
public boolean authenticate(String base,String userName, String password);
/**
* This method is responsible to update telephone number of user.
*
* @return boolean true|false
*/
public User updateTelePhone(String userName, String newNumber);
/**
* This method is responsible to create user.
*/
public boolean createUser(User user);
/**
* This method is responsible to delete user.
*/
public boolean remove(String uid);
}
/**
*
* Copyright © Kaustuv Maji , 2014
* Repos - https://github.com/kaustuvmaji
* Blog - http://kaustuvmaji.blogspot.in
*
*/
package ldap.advance.example;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.stereotype.Component;
/**
* This class implements the @see {@link UserRepository}.
*
* @author KMaji
*
*/
@Component
public class UserRepositoryImpl implements UserRepository {
private static Logger log = Logger.getLogger(UserRepositoryImpl.class);
public UserRepositoryImpl() {
}
@Autowired(required = true)
@Qualifier(value = "ldapTemplate")
private LdapTemplate ldapTemplate;
/**
* (non-Javadoc)
*
* @see ldap.advance.example.UserRepository#getAllUserNames()
*/
@Override
public List<String> getAllUserNames() {
log.info("executing {getAllUserNames}");
LdapQuery query = query().base("ou=users");
List<String> list = ldapTemplate.list(query.base());
log.info("Users -> " + list);
return ldapTemplate.search(query().base("ou=users").where("objectClass").is("person"), new SingleAttributesMapper());
}
/**
* (non-Javadoc)
*
* @see ldap.advance.example.UserRepository#getAllUsers()
*/
@Override
public List<User> getAllUsers() {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
return ldapTemplate.search(DistinguishedName.EMPTY_PATH, "(objectclass=person)", controls, new UserAttributesMapper());
}
/**
* (non-Javadoc)
*
* @see ldap.advance.example.UserRepository#getUserDetails(java.lang.String)
*/
@Override
public User getUserDetails(String userName) {
log.info("executing {getUserDetails}");
List<User> list = ldapTemplate.search(query().base("ou=users").where("uid").is(userName), new UserAttributesMapper());
if (list != null && !list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* (non-Javadoc)
*
* @see ldap.advance.example.UserRepository#getUserDetail(java.lang.String)
*/
@Override
public String getUserDetail(String userName) {
log.info("executing {getUserDetails}");
List<String> results = ldapTemplate.search(query().base("ou=users").where("uid").is(userName), new MultipleAttributesMapper());
if (results != null && !results.isEmpty()) {
return results.get(0);
}
return " userDetails for " + userName + " not found .";
}
/**
* (non-Javadoc)
*
* @see ldap.advance.example.UserRepository#authenticate(java.lang.String,
* java.lang.String)
*/
@Override
public boolean authenticate(String base, String userName, String password) {
log.info("executing {authenticate}");
return ldapTemplate.authenticate(base, "(uid=" + userName + ")", password);
}
/**
* (non-Javadoc)
*
* @see
* ldap.advance.example.UserRepository#updateTelePhone(java.lang.String)
*/
@Override
public User updateTelePhone(String userName, String newNumber) {
log.info("executing {updateTelePhone}");
ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("telephoneNumber", newNumber));
ldapTemplate.modifyAttributes("uid=" + userName + ",ou=users", new ModificationItem[]{item});
return getUserDetails(userName);
}
/**
* (non-Javadoc)
*
* @see
* ldap.advance.example.UserRepository#createUser(ldap.advance.example.User)
*/
@Override
public boolean createUser(User user) {
log.info("executing {createUser}");
Attribute objectClass = new BasicAttribute("objectClass");
{
objectClass.add("top");
objectClass.add("uidObject");
objectClass.add("person");
objectClass.add("organizationalPerson");
}
Attributes userAttributes = new BasicAttributes();
userAttributes.put(objectClass);
userAttributes.put("cn", user.getCn());
userAttributes.put("sn", user.getSn());
userAttributes.put("uid", user.getUid());
userAttributes.put("postalAddress", user.getPostalAddress());
userAttributes.put("telephoneNumber", user.getTelephoneNumber());
userAttributes.put("userPassword", user.getUserPassword().getBytes());
ldapTemplate.bind(bindDN(user.getUid()), null, userAttributes);
return true;
}
/**
* (non-Javadoc)
* @see ldap.advance.example.UserRepository#remove(java.lang.String)
*/
@Override
public boolean remove(String uid) {
ldapTemplate.unbind(bindDN(uid));
return true;
}
public static javax.naming.Name bindDN(String _x){
@SuppressWarnings("deprecation")
javax.naming.Name name = new DistinguishedName("uid=" + _x + ",ou=users");
return name;
}
/**
* This class is responsible to prepare User object after ldap search.
*
* @author KMaji
*
*/
private class UserAttributesMapper implements AttributesMapper<User> {
@Override
public User mapFromAttributes(Attributes attributes) throws NamingException {
User user;
if (attributes == null) {
return null;
}
user = new User();
user.setCn(attributes.get("cn").get().toString());
if (attributes.get("userPassword") != null) {
String userPassword = null;
try {
userPassword = new String((byte[]) attributes.get("userPassword").get(), "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("unable to process", e);
}
user.setUserPassword(userPassword);
}
if (attributes.get("uid") != null) {
user.setUid(attributes.get("uid").get().toString());
}
if (attributes.get("sn") != null) {
user.setSn(attributes.get("sn").get().toString());
}
if (attributes.get("postalAddress") != null) {
user.setPostalAddress(attributes.get("postalAddress").get().toString());
}
if (attributes.get("telephoneNumber") != null) {
user.setTelephoneNumber(attributes.get("telephoneNumber").get().toString());
}
return user;
}
}
/**
* This class is responsible to print only cn .
*
* @author KMaji
*
*/
private class SingleAttributesMapper implements AttributesMapper<String> {
@Override
public String mapFromAttributes(Attributes attrs) throws NamingException {
Attribute cn = attrs.get("cn");
return cn.toString();
}
}
/**
* This class is responsible to print all the content in string format.
*
* @author KMaji
*
*/
private class MultipleAttributesMapper implements AttributesMapper<String> {
@Override
public String mapFromAttributes(Attributes attrs) throws NamingException {
NamingEnumeration<? extends Attribute> all = attrs.getAll();
StringBuffer result = new StringBuffer();
result.append("\n Result { \n");
while (all.hasMore()) {
Attribute id = all.next();
result.append(" \t |_ #" + id.getID() + "= [ " + id.get() + " ] \n");
log.info(id.getID() + "\t | " + id.get());
}
result.append("\n } ");
return result.toString();
}
}
}
| Methods name | Description |
|---|---|
| createUser | This method is responsible to create user. - Example of ldapTemplate.bind() and BasicAttribute. |
| updateTelePhone | This method is responsible to update telephone number of user. - Example of ldapTemplate.modifyAttributes and ModificationItem. |
| remove | This method is responsible to delete user. - Example of ldapTemplate.unbind(). |
| getAllUserNames | This method is responsible to fetch all the user details as a list of String. - ldapTemplate.search() is used to search data. - Example of LdapQueryBuilder. |
| getAllUsers | This method is responsible to fetch all the user details as a list of User object. - ldapTemplate.search() is used to search data. - Example of SearchControls. |
| getUserDetails | This method is responsible to fetch user details of particular user as User Object. - Example of UserAttributesMapper. |
| getUserDetail | This method is responsible to fetch user details of particular user as a string. |
| authenticate | This method is responsible to authenticate user. - Example of ldapTemplate.authenticate(). |
/**
* This class is responsible to prepare User object after ldap search.
*
* @author KMaji
*
*/
private class UserAttributesMapper implements AttributesMapper<User> {
@Override
public User mapFromAttributes(Attributes attributes) throws NamingException {
User user;
if (attributes == null) {
return null;
}
user = new User();
user.setCn(attributes.get("cn").get().toString());
if (attributes.get("userPassword") != null) {
String userPassword = null;
try {
userPassword = new String((byte[]) attributes.get("userPassword").get(), "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("unable to process", e);
}
user.setUserPassword(userPassword);
}
if (attributes.get("uid") != null) {
user.setUid(attributes.get("uid").get().toString());
}
if (attributes.get("sn") != null) {
user.setSn(attributes.get("sn").get().toString());
}
if (attributes.get("postalAddress") != null) {
user.setPostalAddress(attributes.get("postalAddress").get().toString());
}
if (attributes.get("telephoneNumber") != null) {
user.setTelephoneNumber(attributes.get("telephoneNumber").get().toString());
}
return user;
}
}
/**
* This class is responsible to print only cn .
*
* @author KMaji
*
*/
private class SingleAttributesMapper implements AttributesMapper<String> {
@Override
public String mapFromAttributes(Attributes attrs) throws NamingException {
Attribute cn = attrs.get("cn");
return cn.toString();
}
}
/**
* This class is responsible to print all the content in string format.
*
* @author KMaji
*
*/
private class MultipleAttributesMapper implements AttributesMapper<String> {
@Override
public String mapFromAttributes(Attributes attrs) throws NamingException {
NamingEnumeration<? extends Attribute> all = attrs.getAll();
StringBuffer result = new StringBuffer();
result.append("\n Result { \n");
while (all.hasMore()) {
Attribute id = all.next();
result.append(" \t |_ #" + id.getID() + "= [ " + id.get() + " ] \n");
log.info(id.getID() + "\t | " + id.get());
}
result.append("\n } ");
return result.toString();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
#
# Copyright © Kaustuv Maji , 2014
# Repos - https://github.com/kaustuvmaji
# Blog - http://kaustuvmaji.blogspot.in
#
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:ldap="http://www.springframework.org/schema/ldap"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/ldap
http://www.springframework.org/schema/ldap/spring-ldap.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="ldap.advance.example" />
<bean id="simpleDirContextAuthenticationStrategy" class="org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy" />
<bean id="userReposImpl" class="ldap.advance.example.UserRepositoryImpl" />
<ldap:context-source url="ldap://localhost:10389"
base="dc=example,dc=com"
username="uid=admin,ou=system"
password="secret"
authentication-strategy-ref="simpleDirContextAuthenticationStrategy"
native-pooling="true"/>
<!-- A bean identifier, used for referring to the bean elsewhere in the context. Default is "ldapTemplate". -->
<ldap:ldap-template id="ldapTemplate"/>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
</layout>
</appender>
<!-- Appenders -->
<appender name="file" class="org.apache.log4j.RollingFileAppender">
<param name="Threshold" value="ALL" />
<param name="File" value="diag.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="500000KB" />
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
</layout>
</appender>
<!-- Root Logger -->
<root>
<priority value="ALL" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</log4j:configuration>
Post Development testing
Following class will be used to test spring ldap template examples.
/**
*
* Copyright © Kaustuv Maji , 2014
* Repos - https://github.com/kaustuvmaji
* Blog - http://kaustuvmaji.blogspot.in
*
*/
package ldap.advance.example.test;
import java.util.Date;
import ldap.advance.example.User;
import ldap.advance.example.UserRepository;
import org.apache.log4j.Logger;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author KMaji
*
*/
public class LdapApp {
private static Logger log = Logger.getLogger(LdapApp.class);
static String username = "kaustuv";
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-ldap-example.xml");
log.info("Test started at "+new Date(context.getStartupDate()));
UserRepository ldapDao = (UserRepository) context.getBean("userReposImpl");
{
// Create
User user = new User();
{
user.setCn("spring_ldap_test");
user.setSn("spring_ldap_test");
user.setUid("spring_ldap_test");
user.setPostalAddress("spring_ldap_test");
user.setTelephoneNumber("9830098301");
user.setUserPassword("spring_ldap_test");
}
log.info("\n =>" + ldapDao.createUser(user));
// Read
log.info("\n =>" + ldapDao.getAllUsers());
log.info("\n =>" + ldapDao.getAllUserNames());
context.refresh();
log.info("\n =>" + ldapDao.getUserDetails("spring_ldap_test"));
log.info("\n =>" + ldapDao.getUserDetail("spring_ldap_test"));
// Update
log.info("\n =>" + ldapDao.updateTelePhone("kaustuv", "9831198311"));
// Delete
log.info("\n =>" + ldapDao.remove("spring_ldap_test"));
}
context.registerShutdownHook();
context.close();
}
}
Source Code
- References:
European Union laws require you to give European Union visitors information about cookies used on your blog. In many cases, these laws also require you to obtain consent.
As a courtesy, we have added a notice on your blog to explain Google's use of certain Blogger and Google cookies, including use of Google Analytics and AdSense cookies.
No comments:
Post a Comment