Four Ways to Implement Generic Auth in Spring Boot: AOP, Interceptor, Resolver, Filter
This article explains how to add a generic appkey whitelist authentication feature to a Spring Boot web framework using four approaches—traditional AOP, HandlerInterceptor, HandlerMethodArgumentResolver, and Servlet Filter—providing implementation steps, code examples, and a discussion of their execution order.
The article introduces four ways to implement a generic authentication (appkey whitelist) feature in a Spring Boot based web framework: traditional AOP, Interceptor, ArgumentResolver, and Filter, and summarizes their execution order.
Preface
Faced with endless business requirements, the author needed to add a flexible whitelist validation for appkeys, prompting a deep dive into Spring's extensibility mechanisms.
Traditional AOP
Using Spring AOP, a pointcut is defined on controller methods and a before advice checks the whitelist.
Implementation
Declare an aspect class with @Aspect annotation, e.g., WhitelistAspect.
Add a pointcut method whitelistPointcut() that matches methods annotated with @Whitelist.
Define a @Before advice method checkAppkeyWhitelist to perform the whitelist check before the controller method executes.
Example aspect code:
@Aspect
public class WhitelistAspect {
@Before(value = "whitelistPointcut() && @annotation(whitelist)")
public void checkAppkeyWhitelist(JoinPoint joinPoint, Whitelist whitelist) {
// check whitelist logic
}
@Pointcut("@annotation(com.zhenbianshu.Whitelist)")
public void whitelistPointcut() {}
}Apply the @Whitelist annotation on controller methods to trigger the check.
Extension
The annotation can be extended with additional attributes (e.g., uid()) to support other validation criteria. Spring AOP also supports other pointcut expressions ( execution, bean) and advice types ( @Around, @After).
Interceptor
Spring's HandlerInterceptor can intercept requests before controller execution.
Implementation
Define an interceptor class, e.g., WhitelistInterceptor, implementing HandlerInterceptor.
Override preHandle() to retrieve the @Whitelist annotation and perform the whitelist check, returning true to continue.
Optionally override postHandle() and afterCompletion() for post‑processing.
Register the interceptor in a WebMvcConfigurerAdapter implementation.
Interceptor code example:
@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);
// whitelist validation logic
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 order determines when it runs relative to other interceptors.
ArgumentResolver
Spring's HandlerMethodArgumentResolver allows custom binding of method parameters.
Implementation
Create a custom parameter class, e.g., AuthParam, containing appkey fields.
Implement AuthParamResolver that implements HandlerMethodArgumentResolver. supportsParameter() returns true for AuthParam type. resolveArgument() extracts request data, validates the whitelist, and returns an AuthParam instance.
Register the resolver in WebMvcConfigurerAdapter.
Resolver code example:
@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);
// whitelist validation logic
return new AuthParam();
}
}Configuration to add the resolver:
@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new AuthParamResolver());
}
}Extension
The resolver can be combined with other custom arguments and configured alongside interceptors.
Filter
A Servlet Filter operates before Spring's dispatch, requiring implementation of javax.servlet.Filter.
Implementation
Implement the Filter interface, e.g., WhitelistFilter.
In doFilter(), perform whitelist validation and invoke chain.doFilter() to continue the request.
Register the filter via a FilterRegistrationBean in a configuration class.
Filter code example:
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 {
// whitelist check logic
chain.doFilter(request, response);
}
@Override
public void destroy() {}
}Filter registration:
@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;
}
}Summary
The four mechanisms have distinct use cases and execution order: a Servlet Filter runs first, followed by HandlerInterceptor, then HandlerMethodArgumentResolver, and finally Spring AOP pointcuts. Implementing all four in a project confirms this order via logged output.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
