问题
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