@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/blog/**").permitAll() .anyRequest().authenticated() ) .formLogin(formLogin -> formLogin .loginPage("/login") .permitAll() ) .rememberMe(Customizer.withDefaults()); return http.build(); } }不使用 lambda 的等效配置
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests() .requestMatchers("/blog/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .rememberMe(); return http.build(); } }目前来说,Lambda DSL 是配置 Spring Security 的首选方式,现在 Spring Security6 中旧版写法被废弃了,在 Spring Security7 中旧版写法将被移除,也就是未来必须使用 Lambda DSL 来配置。这样做的主要原因有:
3.许多代码库在这两种风格之间切换,这导致了不一致性,使得理解配置变得困难,并经常导致配置错误。
Customizer.withDefaults() 使用 Spring Security 提供的默认值启用安全特性。
@Configuration @EnableWebFluxSecurity public class SecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http .authorizeExchange(exchanges -> exchanges .pathMatchers("/blog/**").permitAll() .anyExchange().authenticated() ) .httpBasic(Customizer.withDefaults()) .formLogin(formLogin -> formLogin .loginPage("/login") ); return http.build(); } }四. Lambda DSL 的优势