I have created a spring boot filter - implements GenericFilterBean
with @Component
annotation.
@Component public class MyAuthenticationFilter extends GenericFilterBean { ... @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { ... } }
The filter is automatically identified by the Spring Boot Framework and works fine for all of the REST API. I want this filter to apply only on a certain URL path, such as /api/secure/*
but I can't find the right way. I tried @WebFilter
but it didn't work. I'm not using XML configuration or servlet initializer - just the annotations.
What would be the correct way to get it working?
The url-pattern element of a servlet-mapping or a filter-mapping associates a filter or servlet with a set of URLs. When a request arrives, the container uses a simple procedure for matching the URL in the request with a url-pattern in the web. xml file.
The solution for excluding URLs from a third-party filter is to wrap it with a new custom filter which just adds the exclude functionality and delegates the filter logic to the wrapped class. // Forward the request to the next filter or servlet in the chain.
You can add a filter like this:
@Bean public FilterRegistrationBean someFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(someFilter()); registration.addUrlPatterns("/url/*"); registration.addInitParameter("paramName", "paramValue"); registration.setName("someFilter"); registration.setOrder(1); return registration; } @Bean(name = "someFilter") public Filter someFilter() { return new SomeFilter(); }
There is another option if you are able to extend OncePerRequestFilter
. For example:
public class SomeFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // your filter logic .... } @Override protected boolean shouldNotFilter(HttpServletRequest request) { String path = request.getServletPath(); return !path.startsWith("/api/secure/"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With