Spring Security 6.0配置升级:解决废弃方法替换问题
Spring Boot 3.0 + Spring Security 6.0 下 SecurityWebFilterChain 重写方案
Spring Security 6.0 废弃了原有的链式调用(依赖.and()串联配置),改用Lambda风格的配置方式,以下是适配后的代码:
@Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, AuthenticationManager authenticationManager) { return http // 禁用CSRF .csrf(csrf -> csrf.disable()) // 请求授权规则配置 .authorizeExchange(exchanges -> exchanges .pathMatchers(HttpMethod.OPTIONS).permitAll() .pathMatchers(publicRoutes).permitAll() .anyExchange().authenticated() ) // 异常处理配置 .exceptionHandling(handling -> handling .authenticationEntryPoint((swe, e) -> { log.error("IN securityWebFilterChain - unauthorized error: {}", e.getMessage()); return Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED)); }) .accessDeniedHandler((swe, e) -> { log.error("IN securityWebFilterChain - access denied: {}", e.getMessage()); return Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN)); }) ) // 添加Bearer认证过滤器 .addFilterAt(bearerAuthenticationFilter(authenticationManager), SecurityWebFiltersOrder.AUTHENTICATION) .build(); }
核心变化说明
- CSRF配置:原
.csrf().disable()改为csrf(csrf -> csrf.disable()),通过Lambda直接配置CsrfSpec - 授权规则:原
.authorizeExchange()链式调用改为authorizeExchange(exchanges -> exchanges...),在Lambda内部定义所有路径匹配规则 - 异常处理:原
.exceptionHandling()链式调用改为exceptionHandling(handling -> handling...),在Lambda内配置认证入口和权限拒绝处理器 - 移除了所有
.and()串联符,Lambda配置天然实现代码块隔离,结构更清晰
内容的提问来源于stack exchange,提问作者flowersin
相关产品推荐
相关产品推荐

