Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply spring boot filter based on URL pattern?

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?

like image 206
user1283002 Avatar asked Sep 26 '16 19:09

user1283002


People also ask

What is URL pattern in filter mapping?

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.

How do I exclude a URL from filter mapping?

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.


2 Answers

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(); } 
like image 54
Ulises Avatar answered Sep 24 '22 16:09

Ulises


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/");     } } 
like image 28
vegemite4me Avatar answered Sep 22 '22 16:09

vegemite4me