Handling Filter Thrown Exceptions in Spring

时间秒杀一切 提交于 2019-12-23 03:44:09

问题


I am trying to implement an Custom ExceptionTranslationFilter in order to handle all of my exception in regards of the authentication ( in which the validity of the toke to be used during authentication happens on my custom filter class). As per searching on the internet there are no available sources for the proper java configuration. Please see my current configuration.

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

Custom Authentication Entry Point Class:

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

Authentication Filter Class:

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

The current problem here is that I am expecting an Error response related to the Unauthorized Http status which is 401 but I am getting the error 500 instead and the exception message and the stack trace is being returned instead.

来源:https://stackoverflow.com/questions/39207743/handling-filter-thrown-exceptions-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!