[英]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, ...);
}
InvalidBearerTokenException
是AuthenticationException
的子类。 知道为什么这个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.