我创建了一个过滤器,用于验证每个请求头的JWT令牌:
public class JWTAuthenticationFilter extends GenericFilterBean {
private UserDetailsService customUserDetailsService;
private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
private final static UrlPathHelper urlPathHelper = new UrlPathHelper();
public JWTAuthenticationFilter(UserDetailsService customUserDetailsService) {
this.customUserDetailsService = customUserDetailsService;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request, customUserDetailsService);
SecurityContextHolder.getContext().setAuthentication(authentication);
if (authentication == null) {
logger.debug("failed authentication while attempting to access " + urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
}
filterChain.doFilter(request, response);
}
}
我想抛出一个自定义异常,并且该异常返回一个响应:
@ResponseStatus(value=HttpStatus.SOMECODE, reason="There was an issue with the provided authentacion information") // 409
public class CustomAuthenticationException extends RuntimeException {
private static final long serialVersionUID = 6699623945573914987L;
}
我该如何做?如何设计最佳方案来捕获过滤器抛出的异常?Spring Security是否提供了任何异常处理机制,我可以使用并在一个点上捕获所有内容?是否有其他方法在过滤器中抛出自定义异常?
注意:这里还有另一个问题,在此处链接 https://stackoverflow.com/questions/40987437/spring-filter-throws-custom-exception。其被接受的答案并没有回答我的问题。我想在到达任何控制器之前返回响应。
我想要处理的错误情况: 1.客户端发送空值的Authorization头。 2.客户端发送格式不正确的令牌。
在这两种情况下,我会收到HTTP状态码为500的响应。我想要得到4XX代码返回。
IllegalArgumentException
,MalformedJwtException
,SignatureException
是一些例子。 - Arian