Four Ways to Implement Generic Auth in Spring Boot: AOP, Interceptor, ArgumentResolver, and Filter

This article reviews four Spring‑Boot techniques—traditional AOP, HandlerInterceptor, custom ArgumentResolver, and Servlet Filter—to implement a reusable app‑key whitelist authentication, provides complete code examples for each, and explains their execution order within the request processing chain.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Four Ways to Implement Generic Auth in Spring Boot: AOP, Interceptor, ArgumentResolver, and Filter

Preface

The article introduces four ways to implement a generic authentication (appkey whitelist) in a Spring‑Boot web framework: traditional AOP, Interceptor, ArgumentResolver, and Filter, and provides corresponding example code together with a brief summary of their execution order.

Recently, overwhelmed by endless business requirements, the author was assigned a task that pushed him out of his comfort zone: adding a generic appkey whitelist validation with better extensibility.

Motivated to document the solution, the author treats the article as a comprehensive review, linking scattered knowledge from the rich Java ecosystem.

Traditional AOP

Using Spring‑Boot's AOP, a pointcut is added before controller methods to perform whitelist checks.

Implementation

Declare an aspect class with @Aspect, e.g., WhitelistAspect.

Define a pointcut method whitelistPointcut() using an annotation @Whitelist so that only annotated methods are checked.

Use @Before to declare a advice method checkWhitelist() that runs before the controller method.

Aspect pseudo‑code:

@Aspect
public class WhitelistAspect {
    @Before(value = "whitelistPointcut() && @annotation(whitelist)")
    public void checkAppkeyWhitelist(JoinPoint joinPoint, Whitelist whitelist) {
        checkWhitelist();
        // joinPoint.getArgs() can retrieve controller arguments
        // whitelist variable provides annotation parameters
    }

    @Pointcut("@annotation(com.zhenbianshu.Whitelist)")
    public void whitelistPointCut() {}
}

Annotate controller methods with @Whitelist to activate the check.

Extension

The annotation can be expanded with additional attributes such as uid() for other whitelist criteria. Spring AOP also supports other pointcut expressions ( execution, bean) and advice types ( @Around, @After).

Interceptor

Spring's HandlerInterceptor can intercept requests before controller actions, making it suitable for whitelist validation.

Implementation

Define an interceptor class WhitelistInterceptor implementing HandlerInterceptor.

Override preHandle() to retrieve the @Whitelist annotation from the handler and perform the check, returning false to block the request.

Register the interceptor in a WebMvcConfigurerAdapter subclass.

Interceptor class:

@Component
public class WhitelistInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Whitelist whitelist = ((HandlerMethod) handler).getMethodAnnotation(Whitelist.class);
        // Perform whitelist validation using request parameters and annotation values
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}

Configuration to add the interceptor:

@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WhitelistInterceptor()).addPathPatterns("/*").order(1);
    }
}

Extension

The interceptor must be explicitly enabled via the configuration class, and its successful execution returns HTTP 200 with an empty body.

ArgumentResolver

Spring's HandlerMethodArgumentResolver allows custom resolution of method parameters before controller execution.

Implementation

Define a custom parameter type AuthParam containing appkey fields.

Create AuthParamResolver implementing HandlerMethodArgumentResolver.

Implement supportsParameter() to match AuthParam.

Implement resolveArgument() to extract request data, validate the whitelist, and return an AuthParam instance.

Add AuthParam as a method argument in controller actions.

Resolver class:

@Component
public class AuthParamResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(AuthParam.class);
    }
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Whitelist whitelist = parameter.getMethodAnnotation(Whitelist.class);
        // Validate whitelist using request and annotation
        return new AuthParam();
    }
}

Register the resolver:

@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new AuthParamResolver());
    }
}

Filter

A Servlet Filter operates at the servlet container level, outside the Spring context.

Implementation

Implement javax.servlet.Filter and perform whitelist checks using the raw ServletRequest and ServletResponse. Remember to invoke FilterChain.doFilter() to continue processing.

public class WhitelistFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Determine whether to block the request
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {}
}

Register the filter:

@Configuration
public class FilterConfiguration {
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new WhitelistFilter());
        registration.addUrlPatterns("/*");
        registration.setName("whitelistFilter");
        registration.setOrder(1);
        return registration;
    }
}

Conclusion

All four implementations have their suitable scenarios. Their invocation order is: Filter (first, as it belongs to the Servlet spec), then Interceptor, followed by ArgumentResolver, and finally the AOP aspect pointcut.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

InterceptorFilterauthArgumentResolverspring-boot
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.