2

Many times, when we are working on company systems or products, we need to create our own user management system. This is not difficult for developers, but when we need to maintain multiple different systems and the same users use across systems, If each system maintains its own user information, then the synchronization of user information will become more troublesome at this time, and it will also be very troublesome for the users themselves, and it is easy for different system passwords to be inconsistent.

If we introduce LDAP to centrally store user's basic information and provide a unified read-write interface and verification mechanism at this time, then this problem will be easier to solve. Especially in the development and construction of some internal management systems, often our internal systems are not all developed by ourselves at the beginning, and there are many third-party product support, such as: OA system, financial system, etc. If you develop a set of user management by yourself System, then the docking of these systems has to be developed again, and the cost is very high. Since LDAP is not a new technology, most mature software supports the use of LDAP to manage users, so today, LDAP applications can still be seen frequently.

Let's take a look specifically at how to access the LDAP server when developing with Spring Boot.

Introduction to LDAP

LDAP (Lightweight Directory Access Protocol, Lightweight Directory Access Protocol) is to provide information services called directory services. Directory service is a special database system that is specifically optimized for reading, browsing and searching operations. Directories are generally used to contain descriptive, attribute-based information and support sophisticated filtering capabilities. The catalog generally does not support the complex transaction management or rollback strategies required by general databases for a large number of update operations. The update of directory services is generally very simple. This kind of directory can store various information including personal information, web links, jpeg images and so on. In order to access the information stored in the directory, it is necessary to use the access protocol-LDAP running on top of TCP/IP.

The information in the LDAP directory is organized in a tree structure, and the specific information is stored in the data structure of the entry. An entry is equivalent to a record in a table in a relational database; an entry is an attribute with a Distinguished Name (DN), which is used to refer to the entry, and the DN is equivalent to a primary key in a relational database table. An attribute is composed of a type (Type) and one or more values (Values), which is equivalent to a field (Field) in a relational database consisting of field names and data types, just to facilitate retrieval, the Type in LDAP can have multiple Values , Rather than in the relational database in order to reduce the redundancy of the data required to achieve the various domains must be unrelated. The organization of entries in LDAP is generally organized according to geographic location and organizational relationship, which is very intuitive. LDAP stores data in files. In order to improve efficiency, an index-based file database can be used instead of a relational database. An example of a type is mail, and its value will be an email address.

LDAP information is stored in a tree structure. The country (c=CN) or domain name (dc=com) is generally defined at the root of the tree, and one or more organizations (o=Acme) or Organizational units (ou=People). An organizational unit may contain information such as all employees, all printers in the building, and so on. In addition, LDAP supports control over which attributes an entry can and must support. This is achieved by a special attribute called objectClass. The value of this attribute determines some rules that the entry must follow, which stipulates which attributes the entry can and should contain at least. For example: the inetorgPerson object class needs to support sn (surname) and cn (common name) attributes, but it can also contain optional attributes such as email and phone number.

LDAP abbreviation corresponds to

  • o: organization (organization-company)
  • ou: organization unit (organization unit-department)
  • c: countryName (country)
  • dc: domainComponent (domain name)
  • sn: surname (surname)
  • cn: common name

above content is referenced from: LDAP Quick Start

Getting started example

After understanding the basic concepts of LDAP, we use a simple example to further understand!

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

<dependency>
    <groupId>com.unboundid</groupId>
    <artifactId>unboundid-ldapsdk</artifactId>
    <scope>test</scope>
</dependency>

Among them, spring-boot-starter-data-ldap is the implementation of LDAP automatic configuration encapsulated by Spring Boot, which is based on spring-data-ldap to perform specific operations on the LDAP server.

And unboundid-ldapsdk mainly to use the embedded LDAP server to perform test operations here, so scope set to test. In actual applications, we usually connect to a real, independently deployed LDAP server, so this dependency is not required.

  • Create a ldap-server.ldif file in the src/test/resources directory to store the basic data of the LDAP server for subsequent program access.
dn: dc=didispace,dc=com
objectClass: top
objectClass: domain
objectclass: extensibleObject
dc: didispace

dn: ou=people,dc=didispace,dc=com
objectclass: top
objectclass: organizationalUnit
ou: people

dn: uid=ben,ou=people,dc=didispace,dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: didi
sn: zhaiyongchao
uid: didi
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=

A basic user is created here. The real name is zhaiyongchao and the common name is didi . In the following program, we will read this information. For more explanations, you can learn more about LDAP to understand, so I won't do too much explanation here.

  • Add the configuration of embedded LDAP in application.properties
spring.ldap.embedded.ldif=classpath:ldap-server.ldif
spring.ldap.embedded.base-dn=dc=didispace,dc=com
  • Use the basic usage of spring-data-ldap to define the relationship mapping between attributes in LDAP and entities defined in our Java and the corresponding Repository
@Data
@Entry(base = "ou=people,dc=didispace,dc=com", objectClasses = "inetOrgPerson")
public class Person {

    @Id
    private Name id;
    @DnAttribute(value = "uid", index = 3)
    private String uid;
    @Attribute(name = "cn")
    private String commonName;
    @Attribute(name = "sn")
    private String userName;
    private String userPassword;

}

public interface PersonRepository extends CrudRepository<Person, Name> {

}

After the above definition, the Person object and the LDAP storage content have been mapped. We only need to use PersonRepository to easily read and write the LDAP content.

  • Create a unit test case to read all user information:
@Slf4j
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private PersonRepository personRepository;

    @Test
    public void findAll() {

        personRepository.findAll().forEach(p -> {
            System.out.println(p);
        });

    }

}

After starting the test case, we can see that the user information ldap-server.ldif

Person(id=uid=ben,ou=people,dc=didispace,dc=com, uid=ben, commonName=didi, userName=zhaiyongchao, userPassword=123,83,72,65,125,110,70,67,101,98,87,106,120,102,97,76,98,72,72,71,49,81,107,53,85,85,52,116,114,98,118,81,61)

Add user

Through the above introductory example, if you can complete it independently, then the basic goal of operating LDAP in Spring Boot has been completed.

If you know enough about Spring Data, in fact, it is not difficult to think that this sub-project under it must also comply with the abstraction of Repsitory. Therefore, we can use the PersonRepository defined above to easily implement operations. For example, the following code can easily add users to LDAP:

Person person = new Person();
person.setUid("uid:1");
person.setSuerName("AAA");
person.setCommonName("aaa");
person.setUserPassword("123456");
personRepository.save(person);

If you want to implement more operations, you can refer to the spring-data-ldap documentation to use it.

Connect to the LDAP server

In the examples in this article, an embedded LDAP server is used. In fact, this method is limited to our local test and development use. In the real environment, the LDAP server must be deployed independently.

Under the encapsulation of Spring Boot, we only need to configure the following parameters to connect the above example to the remote LDAP instead of the embedded LDAP.

spring.ldap.urls=ldap://localhost:1235
spring.ldap.base=dc=didispace,dc=com
spring.ldap.username=didispace
spring.ldap.password=123456

follow me, how to use Spring Security in conjunction with the update later!

This series of tutorials "Spring Boot 2.x Basic Tutorial" click directly! . If you encounter difficulties in the learning process, it is recommended to join Spring Technical Exchange Group , participate in exchanges and discussions, and better study and progress!

Code example

For related examples in this article, you can view the chapter2-8 directory in the following warehouse:

If you think this article is good, welcome Star support, your attention is my motivation for persistence!

Welcome to pay attention to my public account: Program Ape DD, share knowledge and thoughts that can’t be seen elsewhere

程序猿DD
2.2k 声望2.8k 粉丝

作品:《Spring Cloud微服务实战》、SpringForAll社区、OpenWrite、Youtube中文配音