Spring Security 新特性 Lambda DSL 使用

2,642 阅读1分钟

Lambda DSL概述

Spring Security 5.2 对 Lambda DSL 语法的增强,允许使用lambda配置HttpSecurityServerHttpSecurity

重要提醒,之前的配置方法仍然有效。lambda的添加旨在提供更大的灵活性,但是用法是可选的。让我们看一下HttpSecurity的lambda配置与以前的配置样式相比。

HttpSecurity

使用lambdas配置

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/blog/**").permitAll()
                    .anyRequest().authenticated()
            )
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/login")
                    .permitAll()
            )
            .rememberMe(withDefaults());
    }
}

等效配置,不使用lambda

@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/blog/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .rememberMe();
    }
}

默认情况

Lambda DSL配置技巧比较上面的两个样本时,您会注意到一些关键差异:

在Lambda DSL中,无需使用.and()方法链接配置选项。HttpSecurity调用Lambda方法之后实例自动返回进行进一步的配置。

Spring Security WebFlux

@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
            .authorizeExchange(exchanges ->
                exchanges
                    .pathMatchers("/blog/**").permitAll()
                    .anyExchange().authenticated()
            )
            .httpBasic(withDefaults())   //使用提供的默认值启用安全功能
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/login")
            );
        return http.build();
    }
}

总结

Spring SecurityLambda DSL 自动缩进使配置更具可读性、不需要使用链接配置选项.and()。Spring Security DSL与其他Spring DSL(例如Spring Integration和Spring Cloud Gateway)具有类似的配置方法。image