Spring Boot集成Ldap快速入门Demo

2024-05-09 17:04

本文主要是介绍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: openldapimage: osixia/openldap:latestports:- "8389:389"- "8636:636"volumes:- ~/ldap/backup:/data/backup- ~/ldap/data:/var/lib/openldap- ~/ldap/config:/etc/openldap/slapd.d- ~/ldap/certs:/assets/slapd/certscommand: [--copy-service,  --loglevel, debug]phpldapadmin:container_name: phpldapadminimage: osixia/phpldapadmin:latestports:- "8080:80"environment:- PHPLDAPADMIN_HTTPS="false"- PHPLDAPADMIN_LDAP_HOSTS=openldaplinks:- openldapdepends_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 configurationldap:urls: ldap://127.0.0.1:8389base: dc=example,dc=orgusername: cn=admin,${spring.ldap.base}password: adminserver: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*/@Idprivate 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;}

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

代码仓库

  • https://github.com/Harries/springboot-demo

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 {@Autowiredprivate LdapTemplate ldapTemplate;/*** add person*/@Testpublic void addPerson() {Person person = new Person();person.setUid("uid:14");person.setSuerName("LISI");person.setCommonName("lisi");person.setUserPassword("123456");ldapTemplate.create(person);}/*** filter search*/@Testpublic 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() {@Overridepublic 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*/@Testpublic 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() {@Overridepublic 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.引用参考

  • Spring Boot集成Ldap快速入门Demo | Harries Blog™
  • Getting Started | Authenticating a User with LDAP
  • Docker安装LDAP并集成Springboot测试LDAP_ladp dockers-CSDN博客

这篇关于Spring Boot集成Ldap快速入门Demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/973974

相关文章

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

Spring Security方法级安全控制@PreAuthorize注解的灵活运用小结

《SpringSecurity方法级安全控制@PreAuthorize注解的灵活运用小结》本文将带着大家讲解@PreAuthorize注解的核心原理、SpEL表达式机制,并通过的示例代码演示如... 目录1. 前言2. @PreAuthorize 注解简介3. @PreAuthorize 核心原理解析拦截与

一文详解JavaScript中的fetch方法

《一文详解JavaScript中的fetch方法》fetch函数是一个用于在JavaScript中执行HTTP请求的现代API,它提供了一种更简洁、更强大的方式来处理网络请求,:本文主要介绍Jav... 目录前言什么是 fetch 方法基本语法简单的 GET 请求示例代码解释发送 POST 请求示例代码解释

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable

基于SpringBoot+Mybatis实现Mysql分表

《基于SpringBoot+Mybatis实现Mysql分表》这篇文章主要为大家详细介绍了基于SpringBoot+Mybatis实现Mysql分表的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录基本思路定义注解创建ThreadLocal创建拦截器业务处理基本思路1.根据创建时间字段按年进