Issue
I have two endpoints, /health and /save. I don't want to invoke MyFilter for /health endpoint. Below is the code
@Component
public class MyFilter implements Filter {
@Autowired
private JwtConfig jwtConfig;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// do something
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Configuration
@Order(2)
public class WebSecurityConfig extends DefaultSecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.cors().and().csrf().disable().addFilterAfter(new MyFilter(), BasicAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
super.configure(webSecurity);
webSecurity.ignoring().antMatchers("/health/**");
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
The problem is if I remove @component from MyFilter, the filter is not getting invoked for any endpoint and if I put it back it is getting invoked in both endpoints. How can I make it applicable for only /health endpoint ?
Solution
Just on // do something
part, check if requested url is metrics and only do your actions if it is not. The information is readily available in HttpServletRequest
object.
I'm not sure if there are any more straight-forward ways of doing it. Using a FilterRegistrationBean will only allow you to add urls to include, not urls to exclude.
If you do think that you will only have these two endpoints, you can of course use FilterRegistrationBean to only add your save endpoint:
@Bean
public FilterRegistrationBean<MyFilter> myFilter() {
FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new MyFilter());
registrationBean.addUrlPatterns("/save");
return registrationBean;
}
In that case you could remove the Component annotation.
Answered By - eis
Answer Checked By - Willingham (JavaFixing Volunteer)