处理Spring中的过滤器抛出的异常

时间:2016-08-29 13:39:33

标签: java spring filter exception-handling

我正在尝试实现一个Custom ExceptionTranslationFilter,以便处理我在身份验证方面的所有异常(在我的自定义过滤器类中验证期间使用的toke的有效性)。根据在互联网上搜索,没有适当的java配置的可用来源。请参阅我当前的配置。

protected void configure(HttpSecurity http) throws Exception {
    http.anonymous().and()
            .servletApi().and()
            .headers().and()
            .authorizeRequests()
            .antMatchers("/api/login").permitAll()
            .anyRequest().authenticated().and()
            .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class)
            .addFilterAfter(new ExceptionTranslationFilter(new AuthenticationExceptionHandler()),ExceptionTranslationFilter.class);
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

自定义身份验证入口点类:

public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"UNAUTHORIZED");
  }
}

身份验证过滤器类:

public class StatelessAuthenticationFilter extends GenericFilterBean {
public StatelessAuthenticationFilter(TokenAuthenticationService tokenAuthenticationService) {

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, AuthenticationException {
    //I forced my filter to throw this Exception just to test if my 
    ExceptionTranslationFilter in the configuration works.
    throw new MyAuthenticationException("This is a test for filters");
  }
}

这里的当前问题是我期待与未授权的Http状态相关的错误响应,即401,但我得到错误500,而是返回异常消息和堆栈跟踪。

0 个答案:

没有答案