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

MolecularJS技术问题:如何将登录用户传递至Action方法

在MolecularJS动作处理器中传递请求上下文(解码后的Token)

核心解决方案

在MolecularJS的API网关(moleculer-web)authenticate方法中,不要直接覆盖ctx.meta,而是将解码后的Token挂载到ctx.meta的某个属性上,动作处理器就能直接通过ctx.meta获取该数据。

具体代码示例

1. API网关服务配置(设置authenticate方法)

// api.gateway.service.js
const { ApiGateway } = require("moleculer-web");
const jwt = require("jsonwebtoken");

module.exports = {
  name: "api",
  mixins: [ApiGateway],
  settings: {
    routes: [
      {
        path: "/api",
        authentication: true, // 必须开启认证,才会触发authenticate方法
        whitelist: ["user.getProfile"] // 允许访问的动作
      }
    ]
  },
  methods: {
    async authenticate(ctx, route, req, res) {
      // 从请求头提取Token
      const authHeader = req.headers.authorization;
      if (!authHeader || !authHeader.startsWith("Bearer ")) {
        throw new this.errors.UnauthorizedError("NO_TOKEN", { message: "未提供有效Token" });
      }

      const token = authHeader.slice(7);
      try {
        // 解码Token(示例用jsonwebtoken,可替换为你的解码逻辑)
        const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
        
        // 关键:将解码后的Token挂载到ctx.meta的属性上,而非覆盖整个ctx.meta
        ctx.meta.decodedToken = decodedToken;
        
        // 可选:返回用户信息,moleculer-web会自动将其存入ctx.meta.user
        return decodedToken;
      } catch (err) {
        throw new this.errors.UnauthorizedError("INVALID_TOKEN", { message: "Token无效或已过期" });
      }
    }
  }
};

2. 业务服务动作处理器(获取解码后的Token)

// user.service.js
module.exports = {
  name: "user",
  actions: {
    getProfile: {
      handler(ctx) {
        // 直接从ctx.meta获取解码后的Token
        const decodedToken = ctx.meta.decodedToken;
        if (!decodedToken) {
          throw new this.errors.UnauthorizedError("NO_AUTH_DATA", { message: "未获取到认证信息" });
        }

        // 业务逻辑示例:根据Token中的userId查询用户信息
        return this.fetchUserProfile(decodedToken.userId);
      }
    }
  },
  methods: {
    async fetchUserProfile(userId) {
      // 替换为你的数据库查询或业务逻辑
      return {
        userId,
        username: "hariprasad",
        email: "hari@example.com"
      };
    }
  }
};

常见问题排查

  • 不要覆盖整个ctx.meta:如果直接赋值ctx.meta = { decodedToken: xxx },会丢失moleculer-web默认传递的元数据,导致后续传递失败,必须挂载到现有ctx.meta的属性上。
  • 确认路由开启authentication:只有路由配置中authentication: true时,authenticate方法才会执行,否则不会处理Token。
  • 检查Broker配置:确保Broker未禁用元数据传递,默认配置下meta是开启的,若手动修改过brokerOptions,需确认meta相关配置未被禁用。

内容的提问来源于stack exchange,提问作者HariPrasad Katakam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:15:59