Four Ways to Implement Generic Auth in Spring Boot: AOP, Interceptor, ArgumentResolver, and Filter
This article explains how to add a generic app‑key whitelist authentication feature to a Spring Boot web framework using four different mechanisms—traditional AOP, HandlerInterceptor, custom HandlerMethodArgumentResolver, and Servlet Filter—providing implementation steps, code examples, and a discussion of their execution order.
The article introduces four approaches for implementing a generic authentication whitelist in a Spring Boot based web framework: traditional AOP, Interceptor, ArgumentResolver, and Filter, each with sample code and a brief discussion of when each technique is appropriate.
Preface
The author describes a recent requirement to add an extensible app‑key whitelist check to an internal web framework that sits between business code and Spring, and decides to explore several Spring mechanisms to achieve this.
Traditional AOP
Using Spring AOP, a custom aspect is defined with a pointcut that matches methods annotated with @Whitelist . The aspect checks the whitelist before the controller method executes.
Implementation
Steps:
Declare an aspect class with @Aspect (e.g., WhitelistAspect ).
Define a pointcut method whitelistPointcut() that matches the @Whitelist annotation.
Use @Before to run checkWhitelist() before the controller method.
Annotate controller methods with @Whitelist to trigger the check.
@Aspect
public class WhitelistAspect {
@Before(value = "whitelistPointcut() && @annotation(whitelist)")
public void checkAppkeyWhitelist(JoinPoint joinPoint, Whitelist whitelist) {
checkWhitelist();
// joinPoint.getArgs() can be used to get method arguments
// whitelist variable provides annotation parameters
}
@Pointcut("@annotation(com.zhenbianshu.Whitelist)")
public void whitelistPointCut() {}
}Extension
The annotation can be expanded with additional attributes such as uid() to support other whitelist criteria, and other AOP pointcut expressions ( execution , bean ) and advice types ( @Around , @After ) can be used as needed.
Interceptor
Spring's HandlerInterceptor can be used to intercept requests before they reach the controller. The interceptor checks the whitelist and decides whether to continue processing.
Implementation
Create a class WhitelistInterceptor that implements HandlerInterceptor .
Override preHandle() to perform the whitelist check and return false to block the request.
Optionally override postHandle() and afterCompletion() for post‑processing.
Register the interceptor in a WebMvcConfigurerAdapter implementation.
@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; // return false to block the request
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Executed after controller method but before view rendering
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Executed after the view is rendered
}
}Extension
The interceptor must be added to the MVC configuration, for example:
@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WhitelistInterceptor()).addPathPatterns("/*").order(1);
}
}ArgumentResolver
A custom HandlerMethodArgumentResolver can create a typed argument (e.g., AuthParam ) that already contains the validated app‑key, allowing controller methods to declare this parameter directly.
Implementation
Define a custom parameter class AuthParam with fields for the app‑key.
Create AuthParamResolver implementing HandlerMethodArgumentResolver .
Implement supportsParameter() to return true for AuthParam type.
Implement resolveArgument() to extract request data, perform whitelist validation, and return an AuthParam instance.
Add the resolver to MVC configuration.
@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 webRequest and annotation values
return new AuthParam();
}
}Extension
The resolver is registered like this:
@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List
argumentResolvers) {
argumentResolvers.add(new AuthParamResolver());
}
}Filter
A Servlet Filter runs before Spring's dispatch, making it the earliest point in the request chain. It implements javax.servlet.Filter and must explicitly invoke chain.doFilter() to continue processing.
Implementation
public class WhitelistFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// Initialization logic
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Perform whitelist check here
chain.doFilter(request, response); // Continue the chain
}
@Override
public void destroy() {
// Cleanup logic
}
}Extension
Filter registration example:
@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
The execution order is: Filter (Servlet level) → Interceptor → ArgumentResolver → AOP Aspect. The author notes that each technique has its own suitable scenario and reflects on the similarity between these Spring mechanisms and traditional procedural hook patterns.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.