1

I am using a custom JWT filter to pick up cookies from inbound requests, but I'd like to ignore requests to certain paths, for example /authenitcate.

Below is my configuration which excludes the /authenticate path, but I still land in the JWT Filter on calls to it.

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable()
            .logout().disable()
            .authorizeRequests().antMatchers("/").permitAll()
            .antMatchers("/api/*").authenticated()
            .and().exceptionHandling()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authenticate");
}

JwtRequestFilter

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private final Logger log = LoggerFactory.getLogger(JwtRequestFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        Cookie authCookie = WebUtils.getCookie(request, HttpHeaders.AUTHORIZATION);
        String jwtToken = null;
        String username = null;


        if(authCookie != null) {
            jwtToken = authCookie.getValue();
        }

        if (jwtToken != null) {

            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (ExpiredJwtException exception) {
                log.warn("Request to parse expired JWT : {} failed : {}", jwtToken, exception.getMessage());
            } catch (UnsupportedJwtException exception) {
                log.warn("Request to parse unsupported JWT : {} failed : {}", jwtToken, exception.getMessage());
            } catch (MalformedJwtException exception) {
                log.warn("Request to parse invalid JWT : {} failed : {}", jwtToken, exception.getMessage());
            } catch (SignatureException exception) {
                log.warn("Request to parse JWT with invalid signature : {} failed : {}", jwtToken, exception.getMessage());
            } catch (IllegalArgumentException exception) {
                log.warn("Request to parse empty or null JWT : {} failed : {}", jwtToken, exception.getMessage());
            }

        } else {
            logger.warn("JWT Token does not begin with Bearer String");
        }


        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);

            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());

                usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}

Solution

@Bean
    public FilterRegistrationBean<JwtRequestFilter> registration(JwtRequestFilter jwtRequestFilter) {
        FilterRegistrationBean<JwtRequestFilter> registration = new FilterRegistrationBean<JwtRequestFilter>(jwtRequestFilter);
        registration.setEnabled(false);
        return registration;
    }
Half_Duplex
  • 5,102
  • 5
  • 42
  • 58

1 Answers1

1

From your source code, which is not complete in the question, i might suggest that Spring Boot is putting the object jwtRequestFilter automatically into the filter chain (by annotating it with @Bean or @Component) So, although it was correct to exclude/authenticate/in theignoring()` method in security config, that wasn't enough to stop the filter from happening in the context of Spring Boot itself.

The solution is to remove the annotation @Bean or @Component from jwtRequestFilter or to follow the other way explained in Spring Security filter chain not ignoring specified path