I'm working on a spring boot application where I defined my filter to be executed to manage getting and validating the token. So in my Web security class configuration, I managed to do this:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()
// don't create session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
// .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// allow anonymous resource requests
.antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
.antMatchers("/auth/**").permitAll()
.antMatchers("/places/public").permitAll()
.anyRequest().authenticated();
// Custom JWT based security filter
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity.headers().cacheControl();
}
The authenticationTokenFilterBean is a method annotated with @Bean that returns an instance of my filter:
public class JwtFilter extends OncePerRequestFilter{
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtService jwtService;
@Value("${jwt.header}")
private String authorizationHeader;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String token = httpServletRequest.getHeader(authorizationHeader);
String username = jwtService.getUsernameFromToken(token);
if(username!=null && SecurityContextHolder.getContext().getAuthentication() ==null){
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if(jwtService.isTokenValid(token, userDetails)){
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
Since I'm extending OncePerRequestFilter, this filter is invoked only one time per request which is not the case with GenericFilter that need to be executed one time by the servlet and another time with Spring security.
The problem that I have is that the ant matcher described in my configuration class are also intercepted by the filter even if I permit them with the permitAll() method, I tried to override configure(WebSecurity web) method from WebSecurityConfigurerAdapter and ignore them but still didn't work.
How can I configure Spring security to skip my filter for these requests? I already checked this question Spring Security JWT Filter applies on all requests but it has no solution.
Thank you