我正在使用Spring Cloud Gateway和OAuth2 Resource Server构建微服务。该应用程序旨在在完成安全部分后重定向到其他微服务。我试图在AnonymousAuthenticationFilter
之前设置一个过滤器,并从那里处理我的自定义异常,但自定义异常过滤器从未被调用。按照我在应用程序中的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().disable()
.httpBasic().disable()
.formLogin().disable()
.addFilterBefore(customExceptionHandler, AnonymousAuthenticationFilter.class)
.authorizeRequests( auth -> auth.antMatchers(AUTH_WHITELIST).permitAll()
.antMatchers("/**").authenticated())
.oauth2ResourceServer(oauth2ResourceServer -> oauth2ResourceServer.jwt())
.sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
}
在我的customExceptionHandler中,我有以下代码:
public class CustomExceptionHandler extends OncePerRequestFilter {
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
log.error("Spring Security Filter Chain Exception:", e);
resolver.resolveException(request, response, null, e);
}
}
}
以下是我的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-web'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// Spring Cloud
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
我还有一个@ExceptionAdvice
类来处理所有异常。但是,如果我向服务传递一个过期的JWT或任何其他错误场景,我总是在我的WWW-Authenticate
头中得到以下错误消息的处理:
Bearer error="invalid_token", error_description="Jwt expired at 2022-06-16T19:58:09Z", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
如何抛出自定义POJO而不是此消息?
1条答案
按热度按时间8iwquhpp1#
此错误来自
BearerTokenAuthenticationEntryPoint
,因此要覆盖此行为,只需提供一个自定义的entryPoint即可