You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security自定义JWT错误消息返回自定义POJO方案

问题原因
  • 核心原因1:依赖冲突。spring-cloud-starter-gateway是基于WebFlux响应式栈的组件,和你引入的Servlet栈spring-boot-starter-web、spring-boot-starter-data-jpa不兼容,二者混用会导致Spring Security过滤器链注册顺序异常,自定义过滤器无法按预期位置执行。
  • 核心原因2:过滤器配置位置错误。JWT校验逻辑在BearerTokenAuthenticationFilter中执行,该过滤器顺序在AnonymousAuthenticationFilter之前,且默认会自行捕获认证异常(比如JWT过期、签名错误),直接写入WWW-Authenticate响应头,不会将异常抛到上层,所以你加在AnonymousAuthenticationFilter前的异常过滤器根本捕获不到这类异常。
  • 核心原因3:@RestControllerAdvice只能捕获Controller层抛出的异常,Spring Security过滤器链执行在DispatcherServlet之前,过滤器层的异常不会进入Controller异常处理逻辑。
解决方案

第一步:修复依赖冲突

如果使用官方推荐的响应式Spring Cloud Gateway,直接删除Servlet栈相关依赖,build.gradle修改为:

// Spring Boot
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
// 响应式持久层替换JPA,如果不需要持久层可以删掉
// implementation 'org.springframework.boot:spring-boot-starter-data-r2dbc'

// Spring Cloud
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'

如果确实要使用Servlet栈,请替换为Servlet版网关依赖,不要混用WebFlux和Servlet组件。

第二步:通过官方扩展点自定义错误响应

不需要自己编写全局异常捕获过滤器,直接实现OAuth2 Resource Server提供的认证失败入口即可,这是最稳定的实现方式,不会出现过滤器顺序问题。

响应式Stack(适配Spring Cloud Gateway)

  1. 编写自定义认证失败处理器
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

// 自定义错误响应POJO,可根据自己的业务字段调整
class CustomAuthError {
    private Integer code;
    private String message;
    private String path;
    // 自行补充getter、setter
}

@Component
public class CustomAuthEntryPoint implements ServerAuthenticationEntryPoint {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        CustomAuthError error = new CustomAuthError();
        error.setCode(HttpStatus.UNAUTHORIZED.value());
        // 可根据ex的具体异常类型返回不同提示,比如JWT过期、签名非法等
        error.setMessage("认证失败:" + ex.getMessage());
        error.setPath(exchange.getRequest().getPath().value());

        DataBuffer buffer = response.bufferFactory()
                .wrap(objectMapper.writeValueAsBytes(error));
        return response.writeWith(Mono.just(buffer));
    }
}
  1. 注册到Spring Security配置中
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    private static final String[] AUTH_WHITELIST = {"/actuator/**"};

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http,
                                                         CustomAuthEntryPoint authEntryPoint) {
        http.csrf().disable()
                .cors().disable()
                .httpBasic().disable()
                .formLogin().disable()
                .authorizeExchange(exchange -> exchange
                        .pathMatchers(AUTH_WHITELIST).permitAll()
                        .anyExchange().authenticated()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt()
                        .and()
                        .authenticationEntryPoint(authEntryPoint)
                )
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                );
        return http.build();
    }
}

Servlet Stack(如果使用Servlet容器)

  1. 编写自定义认证失败处理器
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

class CustomAuthError {
    private Integer code;
    private String message;
    private String path;
    // 自行补充getter、setter
}

@Component
public class CustomAuthEntryPoint implements AuthenticationEntryPoint {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        CustomAuthError error = new CustomAuthError();
        error.setCode(HttpServletResponse.SC_UNAUTHORIZED);
        error.setMessage("认证失败:" + authException.getMessage());
        error.setPath(request.getRequestURI());

        objectMapper.writeValue(response.getOutputStream(), error);
    }
}
  1. 注册到Spring Security配置中
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {"/actuator/**"};
    @Autowired
    private CustomAuthEntryPoint authEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().disable()
                .httpBasic().disable()
                .formLogin().disable()
                .authorizeRequests(auth -> auth.antMatchers(AUTH_WHITELIST).permitAll()
                        .antMatchers("/**").authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt()
                        .and()
                        .authenticationEntryPoint(authEntryPoint)
                )
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                );
    }
}

补充说明

如果需要处理权限不足(403)的异常,只需要额外实现AccessDeniedHandler(Servlet)或ServerAccessDeniedHandler(WebFlux),通过.oauth2ResourceServer()配置下的accessDeniedHandler()方法注入即可,逻辑和认证失败处理器一致。
如果一定要用自定义过滤器捕获所有Security层异常,需要将过滤器注册到整个Security过滤器链的最前方,也就是添加到WebAsyncManagerIntegrationFilter之前,否则无法捕获到前置过滤器抛出的异常。

内容的提问来源于stack exchange,提问作者mifol68042

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 06:30:38