Escludere endpoints dai filter in Spring Boot

Mattepuffo's logo
Escludere endpoints dai filter in Spring Boot

Escludere endpoints dai filter in Spring Boot

I Filter in Spring Boot sono quelli chiamati middlewares in molti altri framework.

In pratica attraverso i Filter possiamo eseguire delle azioni ad ogni richiesta.

Solo che può accadere che vogliamo escludere alcuni endpoints.

In questo articolo vediamo come fare:

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Order(1)
public class AuthFilter extends OncePerRequestFilter {

  private Set<String> rotteEscluse = new HashSet<>(List.of("/utenti/login"));
  private AntPathMatcher pathMatcher = new AntPathMatcher();

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    
    // DO STUFF

    filterChain.doFilter(request, response);
  }

  @Override
  protected boolean shouldNotFilter(HttpServletRequest request) {
    return rotteEscluse.stream().anyMatch(p -> pathMatcher.match(p, request.getRequestURI()));
  }

}
In sostanza:
  • doFilterInternal -> esegue le nostre operazioni
  • shouldNotFilter -> esclude gli endpoints nella lista
Grazie al forum iProgrammatori per la dritta!

Enjoy!


Condividi

Commentami!