Spring Security 6中仅对自定义端点应用JWT并处理404/403错误
解决方案
一、修正Spring Security配置
首先调整SecurityFilterChain,确保仅你的自定义API端点需要JWT认证,同时内置处理403权限不足的自定义响应逻辑:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth .requestMatchers(endpoints).authenticated() // 仅指定API端点需认证 .anyRequest().permitAll() // 其他请求放行,交由Spring处理404 ) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS) ) .authenticationProvider(authenticationProvider) .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) .exceptionHandling(exceptions -> exceptions // 自定义403响应 .accessDeniedHandler((request, response, ex) -> { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentType(MediaType.APPLICATION_JSON_VALUE); Map<String, Object> error = new HashMap<>(); error.put("status", 403); error.put("message", "无访问权限,请检查JWT令牌是否有效"); new ObjectMapper().writeValue(response.getOutputStream(), error); }) ); return http.build(); }
二、自定义404响应
要让Spring返回自定义404提示,需先开启抛出NoHandlerFoundException,再通过全局异常处理器统一处理:
1. 配置application.properties
添加以下配置,让Spring在找不到请求映射时抛出异常:
spring.mvc.throw-exception-if-no-handler-found=true spring.web.resources.add-mappings=false
2. 创建全局异常处理器
用@ControllerAdvice捕获404异常并返回自定义JSON响应:
@ControllerAdvice public class GlobalErrorHandler { // 处理404资源不存在 @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity<Map<String, Object>> handleNotFound(NoHandlerFoundException ex) { Map<String, Object> error = new HashMap<>(); error.put("status", 404); error.put("message", "请求的资源不存在"); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } // 可选:处理JWT认证失败异常(如令牌无效、过期) @ExceptionHandler(AuthenticationException.class) public ResponseEntity<Map<String, Object>> handleAuthError(AuthenticationException ex) { Map<String, Object> error = new HashMap<>(); error.put("status", 401); error.put("message", "认证失败,请提供有效的JWT令牌"); return new ResponseEntity<>(error, HttpStatus.UNAUTHORIZED); } }
三、关键说明
- 调整Security配置后,非API请求会被放行,Spring找不到对应控制器方法时抛出
NoHandlerFoundException,由全局处理器转为自定义404响应; - API端点的JWT认证失败(如令牌无效)会触发
AuthenticationException,可在全局处理器中统一处理; - 全程利用Spring Security和Spring MVC原生机制实现,无需自定义过滤器,符合最佳实践。
内容的提问来源于stack exchange,提问作者Alan David Cejas
相关产品推荐
相关产品推荐

