springcontrolleradvice未捕获expirerJwtException

问题描述 投票:0回答:1

@ExceptionHandler(DataIntegrityViolationException.class) 公共 ResponseEntity handleRegisterUsernameDuplication(DataIntegrityViolationException e){ 错误对象 错误对象 = 新的错误对象( HttpStatus.CONFLICT.value(), e.getMessage(), 新日期() ); 返回新的 ResponseEntity<>(errorObject, HttpStatus.CONFLICT); }

    @ExceptionHandler(ExpiredJwtException.class)
    public ResponseEntity<ErrorObject> handleJwtExpiration(ExpiredJwtException e){
        ErrorObject errorObject = new ErrorObject(
                HttpStatus.UNAUTHORIZED.value(),
                e.getMessage(),
                new Date()
        );
        return new ResponseEntity<>(errorObject, HttpStatus.UNAUTHORIZED);
    }
}

但是当令牌过期时,使用

403
错误(禁止)而不是我定义的
401
(未经授权),来自服务器:

2023-12-06T17:01:13.459+01:00 ERROR 11489 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception

io.jsonwebtoken.ExpiredJwtException: JWT expired at 2023-12-06T16:01:12Z. Current time: 2023-12-06T16:01:13Z, a difference of 1457 milliseconds.  Allowed clock skew: 0 milliseconds.
    at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:427) ~[jjwt-impl-0.11.5.jar:0.11.5]

...

来自客户:

ERROR
Request failed with status code 403
AxiosError@http://localhost:3000/static/js/bundle.js:66657:18
settle@http://localhost:3000/static/js/bundle.js:67310:12
onloadend@http://localhost:3000/static/js/bundle.js:65992:6
spring-boot exception unauthorized controller-advice
1个回答
0
投票

我怀疑是因为 Spring Security 首先处理该场景。

如果您有

SecurityFilterChain
bean,您应该能够访问
HttpSecurity
并执行以下操作:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .oauth2ResourceServer()
        .authenticationEntryPoint(yourAuthenticationEntryPointGoesHere)
        .and()
        .build();
}

实现

AuthenticationEntryPoint
并自定义
commence
方法。

© www.soinside.com 2019 - 2024. All rights reserved.