Spring Boot 6.1 SecurityConfiguration配置求助(教程代码过时)
Spring Boot Security 适配新版本配置方案
我正在观看Youtube上Amigoscode的Spring Boot Security配置教程,但教程内容略显过时,多数方法已被弃用。我按照教程写出了如下代码,却难以在网上找到解决办法,恳请帮忙配置SecurityConfiguration:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests() .requestMatchers("") .permitAll() .anyRequest() .authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authenticationProvider(authenticationProvider) .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); }
适配新版Spring Security的修正配置
新版Spring Security已弃用大量链式.and()调用写法,推荐使用lambda表达式风格配置,同时你当前的requestMatchers未指定有效路径,以下是修正后的完整配置:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 禁用CSRF(无状态JWT场景适用) .csrf(csrf -> csrf.disable()) // 请求权限规则配置 .authorizeHttpRequests(auth -> auth // 替换为你的实际公开接口路径,比如登录、注册、静态资源等 .requestMatchers("/api/auth/login", "/api/auth/register", "/public/**") .permitAll() // 其余所有请求必须经过认证 .anyRequest() .authenticated() ) // 配置无状态会话(JWT认证核心要求) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS) ) // 绑定自定义认证提供者 .authenticationProvider(authenticationProvider) // 将JWT认证过滤器添加到用户名密码过滤器之前 .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); }
关键说明
- Lambda风格配置:替代旧版
.and()链式调用,完全适配Spring Security 6+的API,彻底消除弃用警告 - 有效路径匹配:
requestMatchers必须传入具体的URL路径或通配符模式,空字符串不会匹配任何请求,会导致所有请求都被要求认证 - 依赖检查:确保
authenticationProvider和jwtAuthFilter已通过构造函数或@Autowired正确注入到配置类中 - 可选跨域配置:如果存在前端跨域需求,可添加CORS配置:
同时定义对应的CORS配置Bean:.cors(cors -> cors.configurationSource(corsConfigurationSource))@Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(List.of("http://localhost:3000")); // 替换为你的前端域名 configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE")); configuration.setAllowedHeaders(List.of("*")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; }
内容的提问来源于stack exchange,提问作者Yordan Yordanov
相关产品推荐
相关产品推荐

