Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom web filter for specific controllers

Help me please, or show other ways to resolve this problem.

@RestController
@RequestMapping("/users")
public class UserController {

    @RequestMapping("/login")
    public String logIn() {
        return "";
    }

    @RequestMapping("/getUserData")
    @FilterThisRequest
    public String getUserData(@PathVariable Long userId) {
        return user;
    }
}

And I have AuthFilter extends GenericFilterBean which makes a certain logic. How can I make that the filter execute only before methods which have @FilterThisRequest? Or there are better practices to resolve this problem?

like image 296
JVic Avatar asked Oct 29 '25 11:10

JVic


2 Answers

Check FilterRegistrationBean reference guide at https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans.

Make FilterRegistrationBean available to Spring via a @Configuration class, the below example will ensure that authFilter runs only for /getUserData. Note that it is URL (and not method) based filtering.

@Autowired AuthFilter authfilter;
....
....
@Bean
public FilterRegistrationBean authFilterRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean(authfilter);
    registration.addUrlPatterns("/web-app-name/getUserData/");
    return registration;
}
like image 129
gargkshitiz Avatar answered Nov 01 '25 12:11

gargkshitiz


I would suggest you for the Interceptor.

@Configuration 
public class Config extends WebMvcConfigurerAdapter {

@Autowired
RequestInterceptor requestInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestInterceptor).addPathPatterns("/getUserData","/user");
    }

}

Interceptor -

@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {


@Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object object) throws Exception {
}

You can override Interceptor's prehandle and postHandle according to your need.

like image 32
JaisAnkit Avatar answered Nov 01 '25 14:11

JaisAnkit