Spring Data Ldap

This commit is contained in:
mokhan 2017-08-14 11:51:46 +05:30
parent a3c47eca35
commit 87cdf5d9dd
8 changed files with 422 additions and 117 deletions

View File

@ -1,131 +1,143 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>spring-ldap</artifactId> <artifactId>spring-ldap</artifactId>
<version>0.1-SNAPSHOT</version> <version>0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
</parent> </parent>
<properties> <properties>
<spring-ldap.version>2.3.1.RELEASE</spring-ldap.version> <spring-ldap.version>2.3.1.RELEASE</spring-ldap.version>
<spring-context.version>4.3.6.RELEASE</spring-context.version> <spring-context.version>4.3.6.RELEASE</spring-context.version>
<apacheds.version>1.5.5</apacheds.version> <apacheds.version>1.5.5</apacheds.version>
<shared-ldap.version>0.9.15</shared-ldap.version> <shared-ldap.version>0.9.15</shared-ldap.version>
</properties> </properties>
<build> <build>
<finalName>spring-ldap</finalName> <finalName>spring-ldap</finalName>
</build> </build>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.ldap</groupId> <groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId> <artifactId>spring-ldap-core</artifactId>
<version>${spring-ldap.version}</version> <version>${spring-ldap.version}</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>commons-logging</groupId> <groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId> <artifactId>commons-logging</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
<version>${spring-context.version}</version> <version>${spring-context.version}</version>
</dependency> </dependency>
<!-- spring ldap test --> <!-- spring ldap test -->
<dependency> <dependency>
<groupId>org.springframework.ldap</groupId> <groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-test</artifactId> <artifactId>spring-ldap-test</artifactId>
<version>${spring-ldap.version}</version> <version>${spring-ldap.version}</version>
<scope>test</scope> <scope>test</scope>
<exclusions> <exclusions>
<exclusion> <exclusion>
<artifactId>commons-logging</artifactId> <artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId> <groupId>commons-logging</groupId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- apacheds for test --> <!-- apacheds for test -->
<dependency> <dependency>
<groupId>org.apache.directory.server</groupId> <groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-core</artifactId> <artifactId>apacheds-core</artifactId>
<version>${apacheds.version}</version> <version>${apacheds.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.directory.server</groupId> <groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-core-entry</artifactId> <artifactId>apacheds-core-entry</artifactId>
<version>${apacheds.version}</version> <version>${apacheds.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.directory.server</groupId> <groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-protocol-shared</artifactId> <artifactId>apacheds-protocol-shared</artifactId>
<version>${apacheds.version}</version> <version>${apacheds.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.directory.server</groupId> <groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-protocol-ldap</artifactId> <artifactId>apacheds-protocol-ldap</artifactId>
<version>${apacheds.version}</version> <version>${apacheds.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.directory.server</groupId> <groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-server-jndi</artifactId> <artifactId>apacheds-server-jndi</artifactId>
<version>${apacheds.version}</version> <version>${apacheds.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.directory.shared</groupId> <groupId>org.apache.directory.shared</groupId>
<artifactId>shared-ldap</artifactId> <artifactId>shared-ldap</artifactId>
<version>${shared-ldap.version}</version> <version>${shared-ldap.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies>
<profiles> <!-- Spring Data LDAP -->
<profile> <dependency>
<id>live</id> <groupId>org.springframework.data</groupId>
<build> <artifactId>spring-data-ldap</artifactId>
<plugins> <version>1.0.6.RELEASE</version>
<plugin> </dependency>
<groupId>org.apache.maven.plugins</groupId> <dependency>
<artifactId>maven-surefire-plugin</artifactId> <groupId>org.springframework.data</groupId>
<executions> <artifactId>spring-data-jpa</artifactId>
<execution> <version>1.11.6.RELEASE</version>
<phase>integration-test</phase> </dependency>
<goals> </dependencies>
<goal>test</goal>
</goals> <profiles>
<configuration> <profile>
<excludes> <id>live</id>
<exclude>**/*IntegrationTest.java</exclude> <build>
</excludes> <plugins>
<includes> <plugin>
<include>**/*LiveTest.java</include> <groupId>org.apache.maven.plugins</groupId>
</includes> <artifactId>maven-surefire-plugin</artifactId>
</configuration> <executions>
</execution> <execution>
</executions> <phase>integration-test</phase>
</plugin> <goals>
</plugins> <goal>test</goal>
</build> </goals>
</profile> <configuration>
</profiles> <excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -0,0 +1,55 @@
package com.baeldung.ldap.data.repository;
import javax.naming.Name;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;
@Entry(base = "ou=users", objectClasses = { "person", "inetOrgPerson", "top" })
public class User {
@Id
private Name id;
private @Attribute(name = "cn") String username;
private @Attribute(name = "sn") String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public Name getId() {
return id;
}
public void setId(Name id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return username;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.ldap.data.repository;
import java.util.List;
import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends LdapRepository<User> {
public User findByUsername(String username);
public User findByUsernameAndPassword(String username, String password);
public List<User> findByUsernameLikeIgnoreCase(String username);
}

View File

@ -0,0 +1,83 @@
package com.baeldung.ldap.data.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.ldap.core.*;
import org.springframework.ldap.support.LdapNameBuilder;
import javax.naming.Name;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.List;
public class LdapClient {
@Autowired
private Environment env;
@Autowired
private ContextSource contextSource;
@Autowired
private LdapTemplate ldapTemplate;
public void authenticate(final String username, final String password) {
contextSource.getContext("cn=" + username + ",ou=users," + env.getRequiredProperty("ldap.partitionSuffix"), password);
}
public List<String> search(final String username) {
return ldapTemplate.search(
"ou=users",
"cn=" + username,
(AttributesMapper<String>) attrs -> (String) attrs
.get("cn")
.get());
}
public void create(final String username, final String password) {
Name dn = LdapNameBuilder
.newInstance()
.add("ou", "users")
.add("cn", username)
.build();
DirContextAdapter context = new DirContextAdapter(dn);
context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
context.setAttributeValue("cn", username);
context.setAttributeValue("sn", username);
context.setAttributeValue("userPassword", digestSHA(password));
ldapTemplate.bind(context);
}
public void modify(final String username, final String password) {
Name dn = LdapNameBuilder
.newInstance()
.add("ou", "users")
.add("cn", username)
.build();
DirContextOperations context = ldapTemplate.lookupContext(dn);
context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
context.setAttributeValue("cn", username);
context.setAttributeValue("sn", username);
context.setAttributeValue("userPassword", digestSHA(password));
ldapTemplate.modifyAttributes(context);
}
private String digestSHA(final String password) {
String base64;
try {
MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(password.getBytes());
base64 = Base64
.getEncoder()
.encodeToString(digest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return "{SHA}" + base64;
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.ldap.data.service;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Service;
import com.baeldung.ldap.data.repository.User;
import com.baeldung.ldap.data.repository.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Boolean authenticate(final String username, final String password) {
User user = userRepository.findByUsernameAndPassword(username, password);
return user != null ? true : false;
}
public List<String> search(final String username) {
List<User> userList = userRepository.findByUsernameLikeIgnoreCase(username);
List<String> users = null;
if (null != userList) {
users = new ArrayList<String>();
for (User user : userList) {
users.add(user.getUsername());
}
}
return users;
}
public void create(final String username, final String password) {
User newUser = new User(username,digestSHA(password));
newUser.setId(LdapUtils.emptyLdapName());
userRepository.save(newUser);
}
public void modify(final String username, final String password) {
User user = userRepository.findByUsername(username);
user.setPassword(password);
userRepository.save(user);
}
private String digestSHA(final String password) {
String base64;
try {
MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(password.getBytes());
base64 = Base64.getEncoder()
.encodeToString(digest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return "{SHA}" + base64;
}
}

View File

@ -7,6 +7,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.data.ldap.repository.config.EnableLdapRepositories;
import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.core.support.LdapContextSource;
@ -16,6 +17,7 @@ import com.baeldung.ldap.client.LdapClient;
@PropertySource("classpath:application.properties") @PropertySource("classpath:application.properties")
@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) @ComponentScan(basePackages = { "com.baeldung.ldap.*" })
@Profile("default") @Profile("default")
@EnableLdapRepositories(basePackages="com.baeldung.ldap.**")
public class AppConfig { public class AppConfig {
@Autowired @Autowired

View File

@ -0,0 +1,68 @@
package com.baeldung.ldap.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.ldap.data.service.UserService;
import com.baeldung.ldap.javaconfig.TestConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("testlive")
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class LdapDataRepositoryTest {
private static final String USER2 = "TEST02";
private static final String USER3 = "TEST03";
private static final String USER4 = "TEST04";
private static final String USER2_PWD = "TEST02";
private static final String USER3_PWD = "TEST03";
private static final String USER4_PWD = "TEST04";
private static final String SEARCH_STRING = "TEST*";
@Autowired
private UserService userService;
@Test
public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() {
Boolean isValid = userService.authenticate(USER3, USER3_PWD);
assertEquals(true, isValid);
}
@Test
public void givenLdapClient_whenIncorrectCredentials_thenFailedLogin() {
Boolean isValid = userService.authenticate(USER3, USER2_PWD);
assertEquals(false, isValid);
}
@Test
public void givenLdapClient_whenCorrectSearchFilter_thenEntriesReturned() {
List<String> userList = userService.search(SEARCH_STRING);
assertThat(userList, Matchers.containsInAnyOrder(USER2, USER3));
}
@Test
public void givenLdapClientNotExists_whenDataProvided_thenNewUserCreated() {
userService.create(USER4, USER4_PWD);
userService.authenticate(USER4, USER4_PWD);
}
@Test
public void givenLdapClientExists_whenDataProvided_thenExistingUserModified() {
userService.modify(USER2, USER3_PWD);
userService.authenticate(USER2, USER3_PWD);
}
}

View File

@ -8,6 +8,7 @@ import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.data.ldap.repository.config.EnableLdapRepositories;
import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.test.TestContextSourceFactoryBean; import org.springframework.ldap.test.TestContextSourceFactoryBean;
@ -17,6 +18,7 @@ import com.baeldung.ldap.client.LdapClient;
@Configuration @Configuration
@PropertySource("classpath:test_application.properties") @PropertySource("classpath:test_application.properties")
@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) @ComponentScan(basePackages = { "com.baeldung.ldap.*" })
@EnableLdapRepositories(basePackages="com.baeldung.ldap.**")
@Profile("testlive") @Profile("testlive")
public class TestConfig { public class TestConfig {
@Autowired @Autowired