【发布时间】:2017-10-17 20:26:33
【问题描述】:
我创建了一个过滤器,用于验证 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 安全提供的异常处理机制,我可以使用并一次性捕获所有内容? 有没有其他方法可以在过滤器中抛出自定义异常?
注意:还有另一个问题here,其接受的答案没有回答我的问题。我想在到达任何控制器之前返回响应。
我要处理的错误情况: 1. 客户端为 Authorization 标头发送一个空值。 2. 客户端发送格式错误的令牌
在这两种情况下,我都会收到带有500 HTTP 状态代码的响应。我想找回4XX 代码。
【问题讨论】:
-
我猜你没有把我的问题读到最后。在最后一段中,我明确给出了该帖子的链接,并说明了为什么该问题有所不同。
-
但是应该是
AuthenticationException来执行失败处理。我在我的问题中添加了一些示例案例。 -
您可以通过添加自定义成功和失败处理程序来做到这一点,并从 AbstractAuthenticationProcessingFilter 扩展您的自定义过滤器
-
@ArianHosseinzadeh 在您的情况下可以抛出哪种类型的异常?
-
IllegalArgumentException,MalformedJwtException,SignatureException是一些例子。