如何自定义 Token 生成策略使用 Redis 而非 Session 存储?

解读

在国内高并发、分布式部署场景下,Session 复制或粘性会话 容易成为性能瓶颈,而 Redis 作为中央式缓存天然支持横向扩展。题目要求“自定义 Token 生成策略”,本质上是让候选人证明:

  1. 能完全接管 Struts2 的 Token 机制(不再依赖 HttpSession);
  2. 生成的 Token 具备防重放、防伪造、可过期特性;
  3. 与 Struts2 的拦截器栈无缝整合,对业务代码零侵入;
  4. 在多节点集群中无状态化,支持水平扩容。

知识点

  • TokenHelper / TokenSessionStore 的扩展点:Struts2 的 org.apache.struts2.util.TokenHelper 只提供静态工具方法,真正存储由 TokenSessionStore 接口实现,默认实现是 org.apache.struts2.interceptor.SessionTokenSessionStore。
  • Redis 数据结构选择:使用 String 类型,Key 规范为 struts:token:{namespace}:{actionName}:{token},Value 存空串或 "1",TTL 由业务设定(如 5 min)。
  • Token 生成算法:国内金融级场景通常要求随机 128 bit + 时间戳 + 业务维度(如用户 ID),再经 Base64URL 编码,确保唯一且不可预测。
  • 线程级缓存:为降低 Redis 往返次数,可在当前线程(ThreadLocal)缓存 Token 校验结果,但提交后必须显式删除。
  • 集群时钟:Redis 过期依赖服务器时钟,要求所有节点开启 NTP 同步,否则可能出现 Token 提前失效。
  • 安全加固:对外暴露的 Token 字段需二次签名(如 HMAC-SHA256),私钥放在配置中心(Nacos、Apollo),防止客户端伪造。

答案

步骤一:定义 RedisTokenSessionStore

public class RedisTokenSessionStore implements TokenSessionStore {
    private static final String PREFIX = "struts:token:";
    private JedisPool jedisPool;          // 或 Lettuce
    private int ttlSeconds = 300;         // 默认 5 分钟

    public void setJedisPool(JedisPool jedisPool) { this.jedisPool = jedisPool; }
    public void setTtlSeconds(int ttlSeconds) { this.ttlSeconds = ttlSeconds; }

    @Override
    public void setToken(String token, HttpServletRequest req) {
        String key = buildKey(token, req);
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.setex(key, ttlSeconds, "1");
        }
    }

    @Override
    public boolean validToken(String token, HttpServletRequest req) {
        String key = buildKey(token, req);
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.del(key) == 1;   // 删除成功表示验证通过
        }
    }

    private String buildKey(String token, HttpServletRequest req) {
        String namespace = req.getParameter(TokenHelper.TOKEN_NAME_FIELD);
        String action    = ActionContext.getContext().getName();
        return PREFIX + namespace + ":" + action + ":" + token;
    }
}

步骤二:在 struts.xml 替换默认存储

<bean type="org.apache.struts2.interceptor.TokenSessionStore" 
      name="redisStore" class="com.xxx.common.web.struts.redis.RedisTokenSessionStore">
    <property name="jedisPool" ref="jedisPool"/>
    <property name="ttlSeconds" value="300"/>
</bean>

<package name="default" extends="struts-default">
    <!-- 使用自定义拦截器栈 -->
    <interceptors>
        <interceptor-stack name="tokenRedisStack">
            <interceptor-ref name="defaultStack"/>
            <interceptor-ref name="token">
                <param name="tokenSessionStore">redisStore</param>
            </interceptor-ref>
        </interceptor-stack>
    </interceptors>

    <default-interceptor-ref name="tokenRedisStack"/>
</package>

步骤三:JSP 端无改动,仍使用 <s:token/> 标签;后端不再操作 Session,实现完全无状态。

拓展思考

  1. 双 Token 机制:在支付、下单等核心场景,可引入一次性 OrderToken(存在 Redis)与幂等性 Idempotency-Key(存在 DB)两级校验,兼顾性能与审计。
  2. 限流与防刷:在 RedisTokenSessionStore 中增加滑动窗口计数器,同一 IP 或用户 1 分钟内生成 Token 超过阈值直接拒绝,返回 429。
  3. 灰度切换:通过配置中心动态切换 SessionTokenSessionStore 与 RedisTokenSessionStore,实现不停机迁移;切换时老 Session 中的 Token 仍可使用,避免用户掉线。
  4. 云原生部署:在 Kubernetes 环境,Redis 使用哨兵或 Cluster 模式,Struts2 应用通过 Sidecar 模式 注入 Redis 地址,支持**Pod 水平自动伸缩(HPA)**而无需关心会话粘滞。
  5. 合规要求:国内等保 2.0 要求敏感操作二次鉴权,可在 Token 验证通过后,再触发一次短信/指纹校验,并把结果写入 Redis 并设置短 TTL(如 60 s),实现“Token + 短凭据”双层防御。