最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringLDAP目錄服務(wù)之LdapTemplate與LDAP操作方式

 更新時(shí)間:2025年04月15日 11:00:39   作者:程序媛學(xué)姐  
本文將深入探討Spring LDAP的核心概念、LdapTemplate的使用方法以及如何執(zhí)行常見(jiàn)的LDAP操作,幫助開(kāi)發(fā)者有效地將LDAP集成到Spring應(yīng)用中,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

引言

在企業(yè)環(huán)境中,輕量級(jí)目錄訪(fǎng)問(wèn)協(xié)議(LDAP)扮演著重要角色,作為集中式用戶(hù)管理和身份驗(yàn)證的標(biāo)準(zhǔn)協(xié)議。LDAP服務(wù)器存儲(chǔ)組織結(jié)構(gòu)化數(shù)據(jù),包括用戶(hù)、組織和權(quán)限信息。

Spring LDAP是Spring家族的一個(gè)子項(xiàng)目,它簡(jiǎn)化了Java應(yīng)用與LDAP服務(wù)器的交互過(guò)程。

一、Spring LDAP基礎(chǔ)

Spring LDAP提供了一個(gè)抽象層,使開(kāi)發(fā)者能夠以Spring風(fēng)格的方式與LDAP交互,避免直接處理底層JNDI API的復(fù)雜性。

它遵循與Spring JDBC相似的模板模式,通過(guò)LdapTemplate提供了簡(jiǎn)潔的接口來(lái)執(zhí)行LDAP操作。

要開(kāi)始使用Spring LDAP,首先需要添加相關(guān)依賴(lài)。對(duì)于Maven項(xiàng)目,可以在pom.xml中添加:

<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
    <version>2.4.1</version>
</dependency>

<!-- 集成Spring Boot -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

在Spring Boot項(xiàng)目中,配置LDAP連接信息可以在application.properties或application.yml中完成:

# LDAP服務(wù)器配置
spring.ldap.urls=ldap://ldap.example.com:389
spring.ldap.base=dc=example,dc=com
spring.ldap.username=cn=admin,dc=example,dc=com
spring.ldap.password=admin_password

二、LdapTemplate詳解

LdapTemplate是Spring LDAP的核心類(lèi),它封裝了LDAP操作的復(fù)雜性,提供了一套簡(jiǎn)潔的API。

在Spring Boot環(huán)境中,LdapTemplate會(huì)被自動(dòng)配置,可以直接注入使用:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;

@Service
public class LdapService {
    
    private final LdapTemplate ldapTemplate;
    
    @Autowired
    public LdapService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    // 使用ldapTemplate執(zhí)行LDAP操作
}

如果不使用Spring Boot,則需要手動(dòng)配置LdapTemplate:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

@Configuration
public class LdapConfig {
    
    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl("ldap://ldap.example.com:389");
        contextSource.setBase("dc=example,dc=com");
        contextSource.setUserDn("cn=admin,dc=example,dc=com");
        contextSource.setPassword("admin_password");
        return contextSource;
    }
    
    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }
}

LdapTemplate提供了多種方法來(lái)執(zhí)行LDAP操作,包括搜索、綁定、修改和刪除等。它還支持回調(diào)方法,允許開(kāi)發(fā)者自定義結(jié)果處理邏輯。

三、LDAP對(duì)象映射

Spring LDAP提供了對(duì)象-目錄映射(ODM)功能,類(lèi)似于ORM(對(duì)象-關(guān)系映射),可以將LDAP條目映射到Java對(duì)象。通過(guò)使用注解,可以輕松實(shí)現(xiàn)LDAP條目與Java類(lèi)之間的轉(zhuǎn)換:

import org.springframework.ldap.odm.annotations.*;
import javax.naming.Name;

@Entry(base = "ou=people", objectClasses = {"person", "inetOrgPerson"})
public class User {
    
    @Id
    private Name id;
    
    @Attribute(name = "cn")
    private String commonName;
    
    @Attribute(name = "sn")
    private String surname;
    
    @Attribute(name = "mail")
    private String email;
    
    @Attribute(name = "telephoneNumber")
    private String phoneNumber;
    
    // Getters and setters
    public Name getId() {
        return id;
    }
    
    public void setId(Name id) {
        this.id = id;
    }
    
    public String getCommonName() {
        return commonName;
    }
    
    public void setCommonName(String commonName) {
        this.commonName = commonName;
    }
    
    // 其他getters和setters
}

在上面的例子中,@Entry注解定義了LDAP條目的基本信息,@Id注解標(biāo)記了條目的唯一標(biāo)識(shí)符,@Attribute注解將Java屬性映射到LDAP屬性。

四、基本LDAP操作

4.1 查詢(xún)操作

使用LdapTemplate進(jìn)行查詢(xún)是最常見(jiàn)的操作??梢允褂酶鞣N方法來(lái)執(zhí)行搜索:

import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.filter.Filter;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.stereotype.Service;

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

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public List<String> getAllUsernames() {
        return ldapTemplate.search(
            "ou=people", // 搜索基礎(chǔ)
            "(objectclass=person)", // 搜索過(guò)濾器
            (AttributesMapper<String>) attrs -> (String) attrs.get("cn").get() // 屬性映射
        );
    }
    
    public List<User> findUserByEmail(String email) {
        Filter filter = new EqualsFilter("mail", email);
        return ldapTemplate.search(
            "ou=people",
            filter.encode(),
            (AttributesMapper<User>) attrs -> {
                User user = new User();
                user.setCommonName((String) attrs.get("cn").get());
                user.setSurname((String) attrs.get("sn").get());
                user.setEmail((String) attrs.get("mail").get());
                return user;
            }
        );
    }
}

使用ODM功能,可以直接將搜索結(jié)果映射到Java對(duì)象:

import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.ldap.query.LdapQueryBuilder;

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public List<User> findUserByEmail(String email) {
        LdapQuery query = LdapQueryBuilder.query()
            .base("ou=people")
            .where("objectclass").is("person")
            .and("mail").is(email);
        
        return ldapTemplate.find(query, User.class);
    }
}

4.2 添加操作

添加新條目可以通過(guò)直接創(chuàng)建對(duì)象然后使用LdapTemplate的create方法:

import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapNameBuilder;

import javax.naming.Name;

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public void createUser(String username, String surname, String email) {
        Name dn = LdapNameBuilder.newInstance()
            .add("ou", "people")
            .add("cn", username)
            .build();
        
        DirContextAdapter context = new DirContextAdapter(dn);
        
        context.setAttributeValues("objectclass", new String[]{"top", "person", "inetOrgPerson"});
        context.setAttributeValue("cn", username);
        context.setAttributeValue("sn", surname);
        context.setAttributeValue("mail", email);
        
        ldapTemplate.bind(context);
    }
}

使用ODM功能,可以更簡(jiǎn)單地創(chuàng)建和保存對(duì)象:

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public void createUser(String username, String surname, String email) {
        User user = new User();
        user.setId(LdapNameBuilder.newInstance()
            .add("cn", username)
            .build());
        user.setCommonName(username);
        user.setSurname(surname);
        user.setEmail(email);
        
        ldapTemplate.create(user);
    }
}

4.3 修改操作

修改現(xiàn)有條目可以通過(guò)查找條目,修改屬性,然后更新:

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public void updateUserEmail(String username, String newEmail) {
        Name dn = LdapNameBuilder.newInstance()
            .add("ou", "people")
            .add("cn", username)
            .build();
        
        DirContextOperations context = ldapTemplate.lookupContext(dn);
        context.setAttributeValue("mail", newEmail);
        
        ldapTemplate.modifyAttributes(context);
    }
}

使用ODM功能:

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public void updateUserEmail(String username, String newEmail) {
        LdapQuery query = LdapQueryBuilder.query()
            .base("ou=people")
            .where("cn").is(username);
        
        User user = ldapTemplate.findOne(query, User.class);
        if (user != null) {
            user.setEmail(newEmail);
            ldapTemplate.update(user);
        }
    }
}

4.4 刪除操作

刪除條目的操作比較簡(jiǎn)單:

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public void deleteUser(String username) {
        Name dn = LdapNameBuilder.newInstance()
            .add("ou", "people")
            .add("cn", username)
            .build();
        
        ldapTemplate.unbind(dn);
    }
}

使用ODM功能:

@Service
public class UserService {
    
    private final LdapTemplate ldapTemplate;
    
    public UserService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }
    
    public void deleteUser(String username) {
        LdapQuery query = LdapQueryBuilder.query()
            .base("ou=people")
            .where("cn").is(username);
        
        User user = ldapTemplate.findOne(query, User.class);
        if (user != null) {
            ldapTemplate.delete(user);
        }
    }
}

五、認(rèn)證與授權(quán)

Spring LDAP可以與Spring Security集成,實(shí)現(xiàn)基于LDAP的認(rèn)證和授權(quán):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .ldapAuthentication()
            .userDnPatterns("cn={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource()
            .url("ldap://ldap.example.com:389/dc=example,dc=com")
            .and()
            .passwordCompare()
            .passwordAttribute("userPassword");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasRole("USER")
            .anyRequest().authenticated()
            .and()
            .formLogin();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 注意:生產(chǎn)環(huán)境不應(yīng)使用NoOpPasswordEncoder
        return NoOpPasswordEncoder.getInstance();
    }
}

六、高級(jí)特性與最佳實(shí)踐

Spring LDAP提供了一些高級(jí)特性,如分頁(yè)查詢(xún)、排序和連接池配置,這些對(duì)于處理大型目錄服務(wù)尤為重要:

// 配置連接池
@Bean
public LdapContextSource contextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldap://ldap.example.com:389");
    contextSource.setBase("dc=example,dc=com");
    contextSource.setUserDn("cn=admin,dc=example,dc=com");
    contextSource.setPassword("admin_password");
    
    // 連接池配置
    contextSource.setPooled(true);
    
    return contextSource;
}

@Bean
public PoolingContextSource poolingContextSource(LdapContextSource contextSource) {
    DefaultTlsDirContextAuthenticationStrategy strategy = new DefaultTlsDirContextAuthenticationStrategy();
    strategy.setHostnameVerifier((hostname, session) -> true);
    contextSource.setAuthenticationStrategy(strategy);
    
    PoolConfig poolConfig = new PoolConfig();
    poolConfig.setMinIdle(5);
    poolConfig.setMaxTotal(20);
    poolConfig.setMaxIdle(10);
    
    PoolingContextSource poolingContextSource = new PoolingContextSource();
    poolingContextSource.setContextSource(contextSource);
    poolingContextSource.setPoolConfig(poolConfig);
    
    return poolingContextSource;
}

// 分頁(yè)查詢(xún)示例
public List<User> findUsersPaged(int pageSize, int pageNumber) {
    PagedResultsDirContextProcessor processor = new PagedResultsDirContextProcessor(pageSize);
    LdapQuery query = LdapQueryBuilder.query()
        .base("ou=people")
        .where("objectclass").is("person");
    
    // 執(zhí)行第一頁(yè)查詢(xún)
    List<User> users = new ArrayList<>();
    for (int i = 0; i < pageNumber; i++) {
        users = ldapTemplate.search(query, new PersonAttributesMapper(), processor);
        
        // 如果沒(méi)有更多結(jié)果或者已經(jīng)到達(dá)請(qǐng)求的頁(yè)碼,則停止
        if (!processor.hasMore() || i == pageNumber - 1) {
            break;
        }
        
        // 設(shè)置cookie以獲取下一頁(yè)
        processor.updateCookie();
    }
    
    return users;
}

總結(jié)

Spring LDAP為開(kāi)發(fā)者提供了一個(gè)強(qiáng)大且靈活的框架,簡(jiǎn)化了與LDAP目錄服務(wù)的交互。通過(guò)LdapTemplate,開(kāi)發(fā)者可以輕松執(zhí)行各種LDAP操作,而無(wú)需深入了解底層JNDI API的復(fù)雜性。對(duì)象-目錄映射功能讓LDAP條目與Java對(duì)象的轉(zhuǎn)換變得簡(jiǎn)單直觀,提高了代碼的可讀性和可維護(hù)性。與Spring Security的集成使得實(shí)現(xiàn)基于LDAP的身份驗(yàn)證和授權(quán)變得輕而易舉。在企業(yè)應(yīng)用中,特別是需要集中式用戶(hù)管理的場(chǎng)景下,Spring LDAP是一個(gè)理想的選擇。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java設(shè)計(jì)模式之Strategy模式

    Java設(shè)計(jì)模式之Strategy模式

    Strategy模式即策略模式,就是將一個(gè)算法的不同實(shí)現(xiàn)封裝成一個(gè)個(gè)單獨(dú)的類(lèi),這些類(lèi)實(shí)現(xiàn)同一個(gè)接口,使用者直接使用該接口來(lái)訪(fǎng)問(wèn)具體的算法。這個(gè)樣子,使用者就可以使用不同的算法來(lái)實(shí)現(xiàn)業(yè)務(wù)邏輯了。
    2016-07-07
  • idea+spring?boot創(chuàng)建項(xiàng)目的搭建全過(guò)程

    idea+spring?boot創(chuàng)建項(xiàng)目的搭建全過(guò)程

    Spring?Boot是Spring社區(qū)發(fā)布的一個(gè)開(kāi)源項(xiàng)目,旨在幫助開(kāi)發(fā)者快速并且更簡(jiǎn)單的構(gòu)建項(xiàng)目,這篇文章主要介紹了idea+spring?boot創(chuàng)建項(xiàng)目的搭建全過(guò)程,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-09-09
  • idea中引入了gb2312編碼的文件的解決方法

    idea中引入了gb2312編碼的文件的解決方法

    這篇文章主要介紹了idea中引入了gb2312編碼的文件的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • MyBatis二級(jí)緩存實(shí)現(xiàn)關(guān)聯(lián)刷新

    MyBatis二級(jí)緩存實(shí)現(xiàn)關(guān)聯(lián)刷新

    本文主要介紹了MyBatis二級(jí)緩存實(shí)現(xiàn)關(guān)聯(lián)刷新,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • SpringMVC處理Form表單實(shí)例

    SpringMVC處理Form表單實(shí)例

    這篇文章主要介紹了使用SpringMVC處理Form表單實(shí)例,非常具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧
    2016-10-10
  • SpringBoot集成ZXing實(shí)現(xiàn)二維碼的生成與讀取功能

    SpringBoot集成ZXing實(shí)現(xiàn)二維碼的生成與讀取功能

    本教程將詳細(xì)講解如何在 Spring Boot 項(xiàng)目中集成 ZXing 庫(kù)實(shí)現(xiàn)二維碼的生成(返回 Base64 編碼)和讀?。ń馕鰣D片的二維碼)功能,并覆蓋常見(jiàn)異常處理、參數(shù)優(yōu)化等實(shí)戰(zhàn)要點(diǎn),適合 Java 開(kāi)發(fā)新手快速上手,需要的朋友可以參考下
    2026-03-03
  • 詳解Spring Data JPA使用@Query注解(Using @Query)

    詳解Spring Data JPA使用@Query注解(Using @Query)

    本篇文章主要介紹了詳解Spring Data JPA使用@Query注解(Using @Query),具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-07-07
  • 微服務(wù)Spring?Cloud?Alibaba?的介紹及主要功能詳解

    微服務(wù)Spring?Cloud?Alibaba?的介紹及主要功能詳解

    Spring?Cloud?是一個(gè)通用的微服務(wù)框架,適合于多種環(huán)境下的開(kāi)發(fā),而?Spring?Cloud?Alibaba?則是為阿里巴巴技術(shù)棧量身定制的解決方案,本文給大家介紹Spring?Cloud?Alibaba?的介紹及主要功能,感興趣的朋友跟隨小編一起看看吧
    2024-08-08
  • spring boot 如何優(yōu)雅關(guān)閉服務(wù)

    spring boot 如何優(yōu)雅關(guān)閉服務(wù)

    這篇文章主要介紹了spring boot 如何優(yōu)雅關(guān)閉服務(wù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • IDEA 2019.2.2配置Maven3.6.2打開(kāi)Maven項(xiàng)目出現(xiàn) Unable to import Maven project的問(wèn)題

    IDEA 2019.2.2配置Maven3.6.2打開(kāi)Maven項(xiàng)目出現(xiàn) Unable to import Maven

    這篇文章主要介紹了IDEA 2019.2.2配置Maven3.6.2打開(kāi)Maven項(xiàng)目出現(xiàn) Unable to import Maven project的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12

最新評(píng)論

阿尔山市| 林口县| 蓝田县| 红原县| 朔州市| 武陟县| 内黄县| 河池市| 宕昌县| 刚察县| 贡觉县| 华池县| 新巴尔虎左旗| 彩票| 永春县| 吴江市| 泗阳县| 鹿泉市| 灵山县| 青冈县| 张北县| 隆德县| 安西县| 专栏| 泸定县| 沭阳县| 和静县| 屏南县| 镇宁| 府谷县| 鄱阳县| 庆云县| 西青区| 常熟市| 麻城市| 迭部县| 通河县| 黄冈市| 会泽县| 聂拉木县| 靖安县|