如何对特定 Method 使用 @SkipAuthentication 注解绕过拦截器?
解读
国内大多数基于 Struts2 的项目会把“登录态校验”做成一个自定义拦截器(如 AuthenticationInterceptor),并配置在默认拦截器栈里,这样所有 Action 请求都会被拦截。
但某些对外接口(如健康检查、支付回调、短信网关)并不需要登录态,此时就要“在方法级精准放行”,而不是把整包 Action 从拦截器栈里摘掉。
面试官问“@SkipAuthentication 怎么用”,表面考注解,实则看你对 Struts2 拦截器执行链、注解映射、MethodFilterInterceptor 扩展机制 是否熟悉,以及能否在不破坏安全的前提下优雅地开“白名单”。
知识点
- Struts2 拦截器栈执行顺序:Action 代理 → 拦截器链 → PreResultListener → Result
- MethodFilterInterceptor 已提供 excludeMethods / includeMethods 配置,可被子类继承
- Struts2 的注解驱动由 Convention Plugin 实现,@Action、@InterceptorRef、@SkipAuthentication 均为运行时标记
- 自定义注解需配合 AnnotationAwareInterceptor 或自己写 AnnotationAuthorizationInterceptor,在 intercept 方法里通过 ActionInvocation.getProxy().getMethod() 反射读取注解
- 放行逻辑务必放在拦截器最前端,且返回 invocation.invoke() 继续下游链;若不放行,直接返回 Action.LOGIN 或 HttpStatus 401
- 生产环境必须 防重复注册:把 @SkipAuthentication 的元注解设为 @Retention(RUNTIME) + @Target(METHOD),避免被类加载器优化掉
- 国内等保要求:即使方法被跳过,仍需保留 访问日志 + 接口鉴权(IP 白名单或 Token),否则审计过不去
答案
步骤一:定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SkipAuthentication {}
步骤二:自定义拦截器继承 MethodFilterInterceptor
public class AuthenticationInterceptor extends MethodFilterInterceptor {
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
// 1. 先读注解
Method m = invocation.getProxy().getAction().getClass()
.getMethod(invocation.getProxy().getMethod());
if (m.isAnnotationPresent(SkipAuthentication.class)) {
return invocation.invoke(); // 直接放行
}
// 2. 正常认证逻辑
Object user = ActionContext.getContext().getSession().get("user");
if (user == null) {
return Action.LOGIN;
}
return invocation.invoke();
}
}
步骤三:在 struts.xml 中声明拦截器并设为默认栈
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="auth" class="com.xxx.AuthenticationInterceptor"/>
<interceptor-stack name="appStack">
<interceptor-ref name="auth"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="appStack"/>
</package>
步骤四:在需要绕过的方法上打注解
@Action("ping")
@SkipAuthentication
public String ping() {
return "json";
}
至此,只有 ping() 方法会跳过认证,其余方法仍被统一拦截,满足“最小权限 + 精准放行”的国内安全规范。
拓展思考
- 如果项目采用 REST 插件,可用 @AllowedMethods 配合 @SkipAuthentication 做“方法级”复合注解,减少 XML 配置
- 高并发场景下,反射读注解会成为热点,建议启动时把 Method -> 是否跳过的布尔值 缓存到 ConcurrentHashMap,实现 一次扫描、运行期 O(1)
- 当接口需要“部分参数跳过,部分参数必须登录”时,可扩展注解为 @SkipAuthentication(roles={"ANON"}),在拦截器里再细判角色,实现 方法级 + 角色级 双维度授权
- 国内金融项目常要求 动态开关,可把注解值写入 Apollo/Nacos,拦截器里实时读取,做到 热更新无损发布
- 面试收尾可主动抛出问题:“如果将来全部迁移到 Spring Boot + Spring Security,是否还保留 @SkipAuthentication 设计?” 体现你对 技术演进 和 兼容策略 的前瞻思考