You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Temporal与Spring Boot中JWT上下文传播问题咨询

问题分析与解决方案

核心问题原因

你遇到的上下文未传播问题并非Temporal的预期行为,根源在于你在ContextPropagator.getCurrentContext()方法中清空SecurityContext的时机错误:

  • 当工作流调度第一个活动时,getCurrentContext被调用,此时你清空了当前线程的SecurityContext
  • 工作流代码继续执行到secondActivity.doSomethingElse()时,当前线程的SecurityContext已经为空,导致第二个活动调度时无法获取到上下文,自然无法传播

Temporal上下文传播的正确流程

Temporal的上下文传播机制在工作流任务生命周期中的执行顺序是:

  1. 工作流任务被分配到线程池中的某一线程时:
    • 先调用ContextPropagator.reset()清理线程可能残留的旧上下文(线程复用场景)
    • 再调用ContextPropagator.setCurrentContext()将持久化的工作流上下文恢复到当前线程
  2. 工作流代码执行过程中,每当需要调度活动/子工作流时:
    • 调用ContextPropagator.getCurrentContext()获取当前上下文,附加到任务头信息中传递
  3. 工作流任务执行完毕(无论成功或失败):
    • 调用ContextPropagator.reset()清理当前线程的上下文,避免线程复用泄露

正确的ContextPropagator实现方式

你需要调整ContextPropagator的实现逻辑,把上下文清理的操作从getCurrentContext移到reset方法中:

public class JwtContextPropagator implements ContextPropagator {

    @Override
    public Object getCurrentContext() {
        // 只读取上下文,不做清空操作
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null && context.getAuthentication() instanceof JwtAuthenticationToken) {
            return ((JwtAuthenticationToken) context.getAuthentication()).getToken().getTokenValue();
        }
        return null;
    }

    @Override
    public void setCurrentContext(Object context) {
        if (context instanceof String jwtToken) {
            // 构造Spring Security的SecurityContext并设置
            JwtAuthenticationToken auth = new JwtAuthenticationToken(JwtDecoder.decode(jwtToken));
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
    }

    @Override
    public void reset() {
        // 工作流任务结束后清理上下文,避免线程复用泄露
        SecurityContextHolder.clearContext();
    }

    @Override
    public String getName() {
        return "JwtContextPropagator";
    }
}

线程复用场景下的传播机制运作

当活动完成后,工作流任务被重新调度到线程池的线程(可能复用旧线程)时:

  1. Temporal先调用reset()方法,清理该线程之前残留的SecurityContext
  2. 再调用setCurrentContext(),把工作流持久化的JWT上下文恢复到当前线程的SecurityContextHolder
  3. 工作流代码继续执行,此时SecurityContext是有效的,调度第二个活动时getCurrentContext能正确获取到JWT,传递到活动中

额外注意事项

  • 确保你的ContextPropagator被正确注册到Temporal的WorkflowClient配置中
  • 活动端的ContextPropagator需要对应实现,在活动执行时把传递的JWT恢复到SecurityContextHolder,执行完毕后同样清理

内容的提问来源于stack exchange,提问作者haydar alaeddine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 14:12:50