Spring Boot集成Ldap快速入门Demo

1.Ldap介绍

LDAP,Lightweight Directory Access Protocol,轻量级目录访问协议.

  1. LDAP是一种特殊的服务器,可以存储数据
  2. 数据的存储是目录形式的,或者可以理解为树状结构(一层套一层)
  3. 一般存储关于用户、用户认证信息、组、用户成员,通常用于用户认证与授权

LDAP简称对应

  • o:organization(组织-公司)
  • ou:organization unit(组织单元-部门)
  • c:countryName(国家)
  • dc:domainComponent(域名)
  • sn:surname(姓氏)
  • cn:common name(常用名称)

2.环境搭建

docker-compose-ldap.yaml

version: '3'

services:
  openldap:
    container_name: openldap
    image: osixia/openldap:latest
    ports:
      - "8389:389"
      - "8636:636"
    volumes:
      - ~/ldap/backup:/data/backup
      - ~/ldap/data:/var/lib/openldap
      - ~/ldap/config:/etc/openldap/slapd.d
      - ~/ldap/certs:/assets/slapd/certs
    command: [--copy-service,  --loglevel, debug]
  phpldapadmin:
    container_name: phpldapadmin
    image: osixia/phpldapadmin:latest
    ports:
      - "8080:80"
    environment:
      - PHPLDAPADMIN_HTTPS="false"
      - PHPLDAPADMIN_LDAP_HOSTS=openldap
    links:
      - openldap
    depends_on:
      - openldap

ldap setup

docker-compose -f docker-compose-ldap.yml -p ldap up -d

open http://localhost:8080/

default account

username:cn=admin,dc=example,dc=org
password:admin

init data

dn: ou=people,dc=exapmple,dc=org
objectClass: top
objectClass: organizationalUnit
ou: people

58

3.代码工程

pom.xml

<?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"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ldap</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--ldap-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

application.yaml


spring:
  application:
    name: spring-demo-ldap
  # ldap configuration
  ldap:
    urls: ldap://127.0.0.1:8389
    base: dc=example,dc=org
    username: cn=admin,${spring.ldap.base}
    password: admin


server:
  port: 8088

Person.java

package com.et.ldap.entity;
 
import lombok.Data;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.DnAttribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;
 
import javax.naming.Name;
import java.io.Serializable;
 

@Data
@Entry(base = "ou=people", objectClasses="inetOrgPerson")
public class Person implements Serializable {
 
    private static final long serialVersionUID = -337113594734127702L;
 
    /**
     *neccesary
     */
    @Id
    private Name id;
 
    @DnAttribute(value = "uid", index = 3)
    private String uid;
 
    @Attribute(name = "cn")
    private String commonName;
 
    @Attribute(name = "sn")
    private String suerName;
 
    private String userPassword;
 
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

4.测试

package com.et.ldap;

import com.et.ldap.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import java.util.List;

import static org.springframework.ldap.query.LdapQueryBuilder.query;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private LdapTemplate ldapTemplate;

    /**
     * add person
     */
    @Test
    public void addPerson() {
        Person person = new Person();
        person.setUid("uid:14");
        person.setSuerName("LISI");
        person.setCommonName("lisi");
        person.setUserPassword("123456");
        ldapTemplate.create(person);
    }
    /**
     * filter search
     */
    @Test
    public void filterSearch() {
        // Get the domain list. If you want to get a certain domain, the filter can be written like this: (&(objectclass=dcObject)&(dc=example))
        // String filter = "(&(objectclass=dcObject))";
        // Get the list of organizations. If you want to get a specific organization, the filter can be written like this: (&(objectclass=organizationalUnit)&(ou=people)
        // String filter = "(&(objectclass=organizationalUnit))";
        //Get the people list. If you want to get a certain person, the filter can be written like this: (&(objectclass=inetOrgPerson)&(uid=uid:13))
        String filter = "(&(objectclass=inetOrgPerson))";
        List<Person> list = ldapTemplate.search("", filter, new AttributesMapper() {
            @Override
            public Object mapFromAttributes(Attributes attributes) throws NamingException, javax.naming.NamingException {
                //如果不知道ldap中有哪些属性,可以使用下面这种方式打印
                NamingEnumeration<? extends Attribute> att = attributes.getAll();
                while (att.hasMore()) {
                    Attribute a = att.next();
                    System.out.println(a.getID() + "=" + a.get());
                }

                Person p = new Person();

                Attribute a = attributes.get("cn");
                if (a != null) p.setCommonName((String) a.get());

                a = attributes.get("uid");
                if (a != null) p.setUid((String) a.get());

                a = attributes.get("sn");
                if (a != null) p.setSuerName((String) a.get());

                a = attributes.get("userPassword");
                if (a != null) p.setUserPassword(a.get().toString());
                return p;
            }
        });

        list.stream().forEach(System.out::println);
    }

    /**
     * query search
     */
    @Test
    public void querySearch() {
        // You can also use filter query method, filter is (&(objectClass=user)(!(objectClass=computer))
        List<Person> personList = ldapTemplate.search(query()
                        .where("objectClass").is("inetOrgPerson")
                        .and("uid").is("uid:14"),
                new AttributesMapper() {
                    @Override
                    public Person mapFromAttributes(Attributes attributes) throws NamingException, javax.naming.NamingException {
                        //If you don’t know what attributes are in ldap, you can print them in the following way
                        // NamingEnumeration<? extends Attribute> att = attr.getAll();
                        //while (att.hasMore()) {
                        //  Attribute a = att.next();
                        // System.out.println(a.getID());
                        //}
                        Person p = new Person();

                        Attribute a = attributes.get("cn");
                        if (a != null) p.setCommonName((String) a.get());

                        a = attributes.get("uid");
                        if (a != null) p.setUid((String) a.get());

                        a = attributes.get("sn");
                        if (a != null) p.setSuerName((String) a.get());

                        a = attributes.get("userPassword");
                        if (a != null) p.setUserPassword(a.get().toString());
                        return p;
                    }
                });
        personList.stream().forEach(System.out::println);
    }
}

运行单元测试类,查看数据,可以看到新增一个人

80

5.引用参考

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
`spring boot demo` 是一个用来深度学习并实战 `spring boot` 的项目,目前总共包含 **`63`** 个集成demo,已经完成 **`51`** 个。 该项目已成功集成 actuator(`监控`)、admin(`可视化监控`)、logback(`日志`)、aopLog(`通过AOP记录web请求日志`)、统一异常处理(`json级别和页面级别`)、freemarker(`模板引擎`)、thymeleaf(`模板引擎`)、Beetl(`模板引擎`)、Enjoy(`模板引擎`)、JdbcTemplate(`通用JDBC操作数据库`)、JPA(`强大的ORM框架`)、mybatis(`强大的ORM框架`)、通用Mapper(`快速操作Mybatis`)、PageHelper(`通用的Mybatis分页插件`)、mybatis-plus(`快速操作Mybatis`)、BeetlSQL(`强大的ORM框架`)、upload(`本地文件上传和七牛云文件上传`)、redis(`缓存`)、ehcache(`缓存`)、email(`发送各种类型邮件`)、task(`基础定时任务`)、quartz(`动态管理定时任务`)、xxl-job(`分布式定时任务`)、swagger(`API接口管理测试`)、security(`基于RBAC的动态权限认证`)、SpringSession(`Session共享`)、Zookeeper(`结合AOP实现分布式锁`)、RabbitMQ(`消息队列`)、Kafka(`消息队列`)、websocket(`服务端推送监控服务器运行信息`)、socket.io(`聊天室`)、ureport2(`中国式报表`)、打包成`war`文件、集成 ElasticSearch(`基本操作和高级查询`)、Async(`异步任务`)、集成Dubbo(`采用官方的starter`)、MongoDB(`文档数据库`)、neo4j(`图数据库`)、docker(`容器化`)、`JPA多数据源`、`Mybatis多数据源`、`代码生成器`、GrayLog(`日志收集`)、JustAuth(`第三方登录`)、LDAP(`增删改查`)、`动态添加/切换数据源`、单机限流(`AOP + Guava RateLimiter`)、ElasticSearch 7.x(`使用官方 Rest High Level Client`)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HBLOGA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值