Spring 引导 - Spring 安全 - InvalidBearerTokenException 错误处理

Spring Boot - Spring Security - InvalidBearerTokenException Error Handling

与这个问题类似,但没有答案:Spring Security: Handle InvalidBearerTokenException in @ExceptionHandler

我有类似的代码,我正在尝试捕捉 org.springframework.security.oauth2.server.resource.InvalidBearerTokenException, when a user has supplied invalid/expired/bad JWT 格式。

    @Component
    public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
        @Autowired
        @Qualifier("handlerExceptionResolver")
        private HandlerExceptionResolver resolver;
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                             AuthenticationException e) throws IOException, ServletException {
    
            resolver.resolveException(request, response, null, e);
        }
    }

    public class SecurityConfig extends WebSecurityConfigurerAdapter
    {
        @Autowired
        private CustomAuthenticationEntryPoint authenticationEntryPoint;
        @Autowired
        private CustomAccessDeniedHandler accessDeniedHandler;
    
        @Override
        protected void configure(HttpSecurity http) throws Exception
        {
            // other config here
            http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2ResourceServer().jwt();
    
            http.exceptionHandling()
                    .authenticationEntryPoint(authenticationEntryPoint)
                    .accessDeniedHandler(accessDeniedHandler);
        }
    }

我还实现了 AuthenticationException@ExceptionHandler 自定义响应。


        @ExceptionHandler({AuthenticationException.class})
        protected ResponseEntity<Object> handleAuthException(AuthenticationException ex, WebRequest req)
        {
            CustomResponse response = ...
            return new ResponseEntity<>(response, ...);
        }

InvalidBearerTokenExceptionAuthenticationException 的子类。 知道为什么这个 AuthenticationEntryPoint 代码没有捕捉到它吗?我还尝试在 commence 方法中添加日志记录,但是当 InvalidBearerTokenException 被抛出时它没有被调用,但是其他 AuthenticationException 会被调用。

您必须在 OAuth2ResourceServerConfigurer 中指定此 AuthenticationEntryPoint,如下所示:

        @Override
        protected void configure(HttpSecurity http) throws Exception
        {
            // other config here
            http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2ResourceServer().jwt().and()
                    .authenticationEntryPoint(authenticationEntryPoint)
                    .accessDeniedHandler(accessDeniedHandler);
        }

当您设置它时,Configurer 将更改 BearerTokenAuthenticationFilter 中使用的 AuthenticationEntryPoint,请参阅 here