Spring 6.2弃用移除exceptionHandler,6.1.2配置JwtEntrypoint失效求助
Spring 6.1.2 配置JwtAuthenticationEntryPoint的正确方式
问题根源
你碰到的写法失效问题,核心是Spring Security 5.7+已弃用WebSecurityConfigurerAdapter,6.x版本彻底移除了该类,原来通过继承该类重写configure(HttpSecurity http)的配置方式已不再适用。
正确配置代码
改用@Bean声明SecurityFilterChain的方式配置HttpSecurity,exceptionHandling().authenticationEntryPoint()方法并未被移除,只是配置入口发生了变化:
import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.List; @EnableWebSecurity public class SecurityConfig { private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; // 构造注入自定义的Jwt认证入口点 public SecurityConfig(JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint) { this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 配置跨域规则 .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 禁用CSRF防护 .csrf(csrf -> csrf.disable()) // 配置异常处理,绑定自定义认证入口点 .exceptionHandling(exceptions -> exceptions .authenticationEntryPoint(jwtAuthenticationEntryPoint) ) // 可追加请求授权规则(示例) .authorizeHttpRequests(auth -> auth .requestMatchers("/api/public/**").permitAll() .anyRequest().authenticated() ); return http.build(); } // 自定义CORS配置(按需调整允许的源、方法、头) @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("http://localhost:3000")); // 替换为你的前端域名 config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("Authorization", "Content-Type")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
关键说明
exceptionHandling()方法依然保留,6.x版本推荐用Lambda风格的配置来设置authenticationEntryPoint- 确保你的
JwtAuthenticationEntryPoint已通过@Component或其他方式声明为Spring Bean - Spring 6.2移除的是旧版
exceptionHandler()方法,而非exceptionHandling(),6.1.2版本中exceptionHandling()完全可用
内容的提问来源于stack exchange,提问作者Obi
相关产品推荐
相关产品推荐

