繁体   English   中英

Spring Boot - Spring Security - InvalidBearerTokenException 错误处理

[英]Spring Boot - Spring Security - InvalidBearerTokenException Error Handling

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

我有类似的代码,当用户提供无效/过期/错误的JWT格式时,我试图捕获org.springframework.security.oauth2.server.resource.InvalidBearerTokenException

    @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);
        }

当您设置它时,配置器将更改BearerTokenAuthenticationFilter内部使用的AuthenticationEntryPoint ,请参见此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM