首页 > 解决方案 > Spring Security WebFlux 和 LDAP

问题描述

为了使用 LDAP 保护反应式 Spring Boot 应用程序,需要进行哪些自定义?到目前为止,我看到的示例都是基于 Spring MVC 的,而用于保护 WebFlux 的示例仅显示了一个带有内存映射的简单响应式示例。

标签: spring-bootspring-securityspring-ldapreactive

解决方案


这是我想出并测试过的一种解决方案。

值得特别注意的是此类中的以下信息:ReactiveAuthenticationManagerAdapter。在那里,它指出:

使 AuthenticationManager 适应反应式 API。这在某种程度上是必要的,因为许多存储凭证的方式(即 JDBC、LDAP 等)没有反应式实现。更重要的是,通常认为最好的做法是将密码存储在故意缓慢的哈希中,这会阻止任何请求进入,除非它被放在另一个线程上。

首先,创建一个配置类。这将处理与 LDAP 的连接。

@Configuration
public class ReactiveLdapAuthenticationConfig {

    // Set this in your application.properties, or hardcode if you want.
    @Value("${spring.ldap.urls}")
    private String ldapUrl;

    @Bean
    ReactiveAuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {

        BindAuthenticator ba = new BindAuthenticator(contextSource);
        ba.setUserDnPatterns(new String[] { "cn={0},ou=people" } );

        LdapAuthenticationProvider lap = new LdapAuthenticationProvider(ba);

        AuthenticationManager am = new ProviderManager(Arrays.asList(lap));

        return new ReactiveAuthenticationManagerAdapter(am);

    }

    @Bean
    BaseLdapPathContextSource contextSource() {
        LdapContextSource ctx = new LdapContextSource();
        ctx.setUrl(ldapUrl);
        ctx.afterPropertiesSet();
        return ctx;
    }

}

之后,您需要按照此处的模式配置安全性。最基本的链配置是这样的:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
        .authorizeExchange()
            .anyExchange().authenticated()
            .and()
        .httpBasic();

    return http.build();
}

为了完整起见,您需要确保拥有这些:

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

其他参考


推荐阅读