Guide to Spring Data LDAP – Spring Data LDAP指南

最后修改: 2017年 8月 20日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this article, we’ll focus on Spring Data LDAP integration and configuration. For a step by step introduction to Spring LDAP, have a quick look at this article.

在本文中,我们将专注于Spring Data LDAP的集成和配置。有关Spring LDAP的逐步介绍,请快速浏览这篇文章

Also, you can find the overview of Spring Data JPA guide here.

此外,您还可以在这里找到Spring Data JPA指南概述

2. Maven Dependency

2.Maven依赖性

Let’s begin by adding the required Maven dependencies:

我们首先添加所需的Maven依赖项。

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-ldap</artifactId>
    <version>2.6.2</version>
</dependency>

The latest versions can be found here for spring-data-ldap.

最新的版本可以在这里找到spring-data-ldap>。

3. Domain Entry

3.域的输入

Spring LDAP project provides an ability to map LDAP entries to Java objects by using Object-Directory Mapping (ODM).

Spring LDAP项目通过使用Object-Directory Mapping(ODM),提供了将LDAP条目映射到Java对象的能力。

Let’s define the entity which will be used to map LDAP directories which have already been configured in the Spring LDAP article.

让我们定义实体,它将用于映射LDAP目录,这些目录已经在Spring LDAP文章中配置好了。

@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;

    // standard getters/setters
}

@Entry is similar to @Entity (of JPA/ORM) which is used to specify which entity maps to directory root of the LDAP entries.

@Entry@Entity(JPA/ORM的)类似,后者用于指定哪个实体映射到LDAP条目的目录根。

An Entry class must have @Id annotation declared on a field of type javax.naming.Name which represents entity DN. The @Attribute annotation is used to map object class fields to entity fields.

一个Entry类必须在代表实体DN的javax.naming.Name类型的字段上声明@Id注释。@Attribute注解用于将对象类字段映射到实体字段。

4. Spring Data Repository

4.Spring Data Repository

Spring Data Repository is an abstraction which provides basic out-of-the-box ready to use implementation of data access layers for various persistence stores.

Spring Data Repository是一个抽象概念,它为各种持久性存储提供了基本的开箱即用的数据访问层实现。

Spring Framework internally provides the implementation of CRUD operations for given class in the data repository. We can find the complete detail in Introduction to Spring Data JPA article.

Spring框架在内部为数据存储库中的指定类提供CRUD操作的实现。我们可以在Introduction to Spring Data JPA文章中找到完整的细节。

Spring Data LDAP provides similar abstraction which provides the automatic implementation of Repository interfaces that include basic CRUD operation for LDAP directories.

Spring Data LDAP提供了类似的抽象,它提供了自动实现Repository接口,包括对LDAP目录的基本CRUD操作。

Also, Spring Data Framework can create a custom query based on a method name.

另外,Spring Data Framework可以根据方法名称创建custom query

Let’s define our repository interface which will be used to manage User Entry:

让我们定义我们的存储库接口,它将被用来管理用户条目:

@Repository
public interface UserRepository extends LdapRepository<User> {
    User findByUsername(String username);
    User findByUsernameAndPassword(String username, String password);
    List<User> findByUsernameLikeIgnoreCase(String username);
}

As we can see, we have declared an interface by extending LdapRepository for entry User. Spring Data Framework will automatically provide basic CRUD method implementation such as find(), findAll(), save(), delete(), etc.

正如我们所看到的,我们通过扩展LdapRepository为条目User声明了一个接口。Spring数据框架将自动提供基本的CRUD方法实现,如find(), findAll(), save(), delete()等。

Also, we have declared a few custom methods. Spring Data Framework will provide the implementation by probing the method name with a strategy known as Query Builder Mechanism.

此外,我们还声明了一些自定义方法。Spring Data Framework将通过探测方法名称来提供实现,该策略被称为Query Builder机制

5. Configuration

5.配置

We can configure Spring Data LDAP using Java-based @Configuration classes or an XML namespace. Let’s configure the repository using the Java-based approach:

我们可以使用基于Java的@Configuration类或XML命名空间来配置Spring Data LDAP。让我们使用基于Java的方法来配置存储库。

@Configuration
@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**")
public class AppConfig {
}

@EnableLdapRepositories hints Spring to scan the given package for interfaces marked as @Repository.

@EnableLdapRepositories提示Spring扫描给定的包,以寻找标记为@Repository.的接口。

6. Using Spring Boot

6.使用Spring Boot

When working on a Spring Boot project, we can use Spring Boot Starter Data Ldap dependency that will automatically instrument LdapContextSource and LdapTemplate for us. 

在进行Spring Boot项目时,我们可以使用Spring Boot Starter Data Ldap依赖,它将自动为我们提供LdapContextSourceLdapTemplate

To enable autoconfiguration, we need to ensure that we have the spring-boot-starter-data-ldap Starter or spring-ldap-core defined as a dependency in our pom.xml:

为了启用自动配置,我们需要确保我们有spring-boot-starter-data-ldap Starter或spring-ldap-core在我们的pom.xml中定义为一个依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

To connect to LDAP, we need to provide the connection settings in the application.properties:

为了连接到LDAP,我们需要在application.properties中提供连接设置。

spring.ldap.url=ldap://localhost:18889
spring.ldap.base=dc=example,dc=com
spring.ldap.username=uid=admin,ou=system
spring.ldap.password=secret

More details about Spring Data LDAP autoconfiguration can be found in the official documentation. Spring Boot brings in LdapAutoConfiguration which takes care of instrumentation of LdapTemplate which can then be injected into the required service class:

关于Spring Data LDAP自动配置的更多细节可以在官方文档中找到。Spring Boot带来了LdapAutoConfiguration,它负责LdapTemplate的工具化,然后可将其注入所需的服务类中。

@Autowired
private LdapTemplate ldapTemplate;

7. Business Logic

7.业务逻辑

Let’s define our service class which will use the UserRepository to operate on LDAP directories:

让我们定义我们的服务类,它将使用UserRepository来操作LDAP目录。

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    // business methods
}

Now, we will explore one action at a time and see how easily we can perform these action using Spring Data Repository

现在,我们将一次探索一个行动,看看我们如何轻松地使用Spring Data Repository执行这些行动。

7.1. User Authentication

7.1.用户认证

Let’s now implement a simple piece of logic to authenticate an existing user:

现在让我们实现一个简单的逻辑来验证一个现有的用户。

public Boolean authenticate(String u, String p) {
    return userRepository.findByUsernameAndPassword(u, p) != null;
}

7.2. User Creation

7.2.用户创建

Next, let’s create a new user and store a password’s hash:

接下来,让我们创建一个新的用户并存储一个密码的哈希值。

public void create(String username, String password) {
    User newUser = new User(username,digestSHA(password));
    newUser.setId(LdapUtils.emptyLdapName());
    userRepository.save(newUser);
}

7.3. User Modification

7.3.用户修改

We can modify an existing user or entry with the following method:

我们可以用以下方法修改一个现有的用户或条目。

public void modify(String u, String p) {
    User user = userRepository.findByUsername(u);
    user.setPassword(p);
    userRepository.save(user);
}

7.4. User Search

7.4.用户搜索

We can search for existing users using a custom method:

我们可以使用一个自定义的方法来搜索现有的用户。

public List<String> search(String u) {
    List<User> userList = userRepository
      .findByUsernameLikeIgnoreCase(u);
    
    if (userList == null) {
        return Collections.emptyList();
    }

    return userList.stream()
      .map(User::getUsername)
      .collect(Collectors.toList());  
}

8. Example in Action

8.行动中的例子

Finally, we can quickly test a simple authentication scenario:

最后,我们可以快速测试一个简单的认证场景。

@Test
public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() {
    Boolean isValid = userService.authenticate(USER3, USER3_PWD);
 
    assertEquals(true, isValid);
}

9. Conclusion

9.结论

This quick tutorial demonstrated the basics of Spring LDAP repository configuration and CRUD operation.

这个快速教程演示了Spring LDAP资源库配置和CRUD操作的基础知识。

The example used in this article can be found over on GitHub.

本文中使用的例子可以在GitHub上找到over