Spring Boot应用程序集成LDAP

以下是一个Spring Boot应用程序,集成LDAP实现用户信息存储和查询的示例。我们将使用Spring Data LDAP模块来与LDAP服务器进行交互。

docker compose 安装 openldap

使用docker compose 安装并启动 openldap :

ldap-compose.yml 文件内容:

version: '3'

services:
  #ldap服务
  openldap:
    image: osixia/openldap
    container_name: openldap-server
    hostname: ldap-server
    networks:
      - ldap
    ports:
      - '389:389'
      - '636:636'
    environment:
      - LDAP_ORGANISATION=baidu  #组织名称,需要改
      - LDAP_DOMAIN=baidu.com    #域名,需要改
      - LDAP_ADMIN_USERNAME=admin
      - LDAP_ADMIN_PASSWORD=123456

  #页面管理
  phpldapadmin:
    image: osixia/phpldapadmin
    container_name: openldap-admin
    hostname: ldap-admin
    privileged: true #授予真实root权限
    networks:
      - ldap
    ports:
      - '18080:80'
      - '443:443'  #PHPLDAPADMIN_HTTPS为true有效
    environment:
      - PHPLDAPADMIN_HTTPS=false
      - PHPLDAPADMIN_LDAP_HOSTS=ldap-server   #指向openldap的hostname
    depends_on:
      - openldap

networks:
  ldap:
    driver: bridge

启动容器:

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

创建Spring Boot项目

首先,确保你在项目的pom.xml文件中添加了以下依赖:

    <dependencies>
        <!-- Spring Boot Starter Data LDAP -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>

        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Lombok (可选) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.12.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

配置LDAP连接

application.properties文件中添加LDAP相关的配置:

spring.ldap.urls=ldap://localhost:50389/
spring.ldap.base=dc=baidu,dc=com
spring.ldap.username=cn=admin,dc=baidu,dc=com
spring.ldap.password=123456

创建实体类

创建一个实体类,它将映射到LDAP中的条目:

package com.example.ldapdemo.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.DnAttribute;

import javax.naming.Name;

@Data
@Entry(base = "ou=people", objectClasses = {"inetOrgPerson","top"})
public class Person {

    @Id
    @JsonIgnore
    private Name id;

    @DnAttribute(value = "uid", index = 1)
    private String uid;

    @Attribute(name = "cn")
    private String fullName;

    @Attribute(name = "sn")
    private String lastName;

    @Attribute(name = "userPassword")
    private String password;
}

创建Repository接口

创建一个Spring Data LDAP repository接口:

package com.example.ldapdemo.repository;

import com.example.ldapdemo.model.Person;
import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends LdapRepository<Person> {
    List<Person> findByLastName(String lastName);

    Person findByUid(String uid);

    void deleteByUid(String uid);
}

创建服务层

创建一个服务层来封装业务逻辑:

package com.example.ldapdemo.service;

import com.example.ldapdemo.model.Person;
import com.example.ldapdemo.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {

    @Autowired
    private PersonRepository personRepository;

    public Person savePerson(Person person) {
        return personRepository.save(person);
    }

    public Person getPersonByUid(String uid) {
        return personRepository.findByUid(uid);
    }

    public List<Person> getAllPersons() {
        return (List<Person>) personRepository.findAll();
    }

    public List<Person> getPersonsByLastName(String lastName) {
        return personRepository.findByLastName(lastName);
    }

    public void deletePerson(String uid) {
        personRepository.deleteByUid(uid);
    }
}

创建控制器

创建一个控制器来处理HTTP请求:

package com.example.ldapdemo.controller;

import com.example.ldapdemo.model.Person;
import com.example.ldapdemo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/persons")
public class PersonController {

    @Autowired
    private PersonService personService;

    @PostMapping
    public Person savePerson(@RequestBody Person person) {
        return personService.savePerson(person);
    }

    @GetMapping("/{uid}")
    public Person getPersonByUid(@PathVariable String uid) {
        return personService.getPersonByUid(uid);
    }

    @GetMapping
    public List<Person> getAllPersons() {
        return personService.getAllPersons();
    }

    @GetMapping("/search")
    public List<Person> getPersonsByLastName(@RequestParam String lastName) {
        return personService.getPersonsByLastName(lastName);
    }

    @DeleteMapping("/{uid}")
    public String deletePerson(@PathVariable String uid) {
        personService.deletePerson(uid);
        return "Person deleted successfully!";
    }
}

Spring Boot 主类

创建Spring Boot应用程序的主类:

package com.example.ldapdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LdapDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(LdapDemoApplication.class, args);
    }
}

运行应用程序

启动Spring Boot应用程序。你可以使用Postman或其他HTTP客户端来测试API:

  • 存储数据

    POST http://localhost:8080/persons
    Body: 
    {
      "uid": "johndoe",
      "fullName": "John Doe",
      "lastName": "Doe",
      "password": "password"
    }
    
  • 查询数据

    GET http://localhost:8080/persons/{uid}
    
  • 查询所有数据

    GET http://localhost:8080/persons
    
  • 按姓氏查询数据

    GET http://localhost:8080/persons/search?lastName=Doe
    
  • 删除数据

    DELETE http://localhost:8080/persons/{uid}
    

解释

  1. 依赖管理

    • 使用Spring Boot Starter Data LDAP简化LDAP服务器的交互。
    • 使用Spring Boot Starter Web简化Web应用开发。
  2. 配置

    • application.properties中指定LDAP服务器的URL、基准DN、用户名和密码。
  3. 实体类

    • 创建一个简单的Person类,并使用注解将其映射到LDAP中的条目。
  4. Repository接口

    • 使用Spring Data LDAP repository接口简化数据访问操作。
  5. 服务层

    • 封装业务逻辑,提供数据存储和查询的高层接口。
  6. 控制器

    • 处理HTTP请求,提供RESTful API进行数据存储和查询。

通过这个示例,你可以轻松地使用Spring Boot集成LDAP来实现用户信息的存储和查询功能。

  • 34
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Spring Boot集成LDAP并支持SSL的示例程序: 1. 首先需要在pom.xml文件中添加LDAP和SSL依赖: ``` <dependency> <groupId>org.springframework.ldap</groupId> <artifactId>spring-ldap-core</artifactId> <version>2.3.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-ldap</artifactId> <version>5.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.2.2.RELEASE</version> </dependency> ``` 2. 在application.yml文件中配置LDAP连接和SSL支持: ``` spring: ldap: urls: ldap://localhost:389 base: dc=example,dc=com username: cn=admin,dc=example,dc=com password: adminPassword # SSL configuration # trust-store: your-trust-store.jks # trust-store-password: trust-store-password # trust-store-type: JKS # key-store: your-keystore.jks # key-store-password: key-store-password # key-store-type: JKS # key-password: key-password server: port: 8080 ``` 3. 创建一个UserService类来与LDAP进行交互: ``` @Service public class UserService { @Autowired private LdapTemplate ldapTemplate; public List<String> getAllUsernames() { List<String> usernames = new ArrayList<>(); ldapTemplate.search( Query.query().where("objectclass").is("person"), (AttributesMapper<Void>) attrs -> { usernames.add((String) attrs.get("cn").get()); return null; }); return usernames; } } ``` 4. 创建一个Controller类来测试UserService类: ``` @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public List<String> getAllUsers() { return userService.getAllUsernames(); } } ``` 这是一个基本的Spring Boot集成LDAP并支持SSL的示例程序,你可以根据自己的需求进行修改和扩展。注意,需要根据你的实际情况来配置SSL相关的参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值