【问题标题】:Service to service authentication in (hapi+molecular) NodeJS(hapi + molecular)NodeJS中的服务到服务身份验证
【发布时间】:2019-11-01 01:03:43
【问题描述】:

我在 Hapi+Molecular 中开发了不同的微服务。 我使用 hapi-moleculer npm 模块在 hapi 中添加分子,我使用 redis 作为传输服务之间的通信。 我可以从服务 B 调用服务 A 的功能... 我需要的是添加身份验证来调用其他服务的功能。 就像服务 B 的服务 A 调用函数一样,它需要进行身份验证以防止其他人连接到我的服务。 我正在调用这样的服务

request.broker.call('users.logout', { });

我看到了一个 imicros-auth 模块,但我没有发现它有多大用处,是否有任何其他模块可以做到这一点,或者是否有更好的方法来自定义代码以进行服务到服务身份验证. 应该是这样的

如果服务调用自己的函数,则不需要认证,如果调用其他服务的函数,则必须认证 还有一件事不应该像从数据库中获取身份验证或某种使服务响应缓慢的东西,可以是基于令牌的或类似的东西

【问题讨论】:

    标签: node.js authentication microservices hapijs moleculer


    【解决方案1】:

    也许这个中间件? https://github.com/icebob/moleculer-protect-services

    要使用它,您应该为所有服务生成一个带有服务名称的 JWT 令牌,并定义一个允许服务的列表。中间件将验证 JWT。

    这里是中间件的来源:

    const { MoleculerClientError } = require("moleculer").Errors;
    
    module.exports = {
    
        // Wrap local action handlers (legacy middleware handler)
        localAction(next, action) {
            // If this feature enabled
            if (action.restricted) {
    
                // Create new handler
                return async function ServiceGuardMiddleware(ctx) {
                    // Check the service auth token in Context meta
                    const token = ctx.meta.$authToken;
                    if (!token)
                        throw new MoleculerClientError("Service token is missing", 401, "TOKEN_MISSING");
    
                    // Verify token & restricted services
                    // Tip: For better performance, you can cache the response because it won't change in runtime.
                    await ctx.call("guard.check", { token, services: action.restricted })
    
                    // Call the original handler
                    return await next(ctx);
    
                }.bind(this);
            }
    
            // Return original handler, because feature is disabled
            return next;
        },
    
        // Wrap broker.call method
        call(next) {
            // Create new handler
            return async function(actionName, params, opts = {}) {
                // Put the service auth token in the meta
                if (opts.parentCtx) {
                    const service = opts.parentCtx.service;
                    const token = service.schema.authToken;
    
                    if (!opts.meta)
                        opts.meta = {};
    
                    opts.meta.$authToken = token;
                }
    
                // Call the original handler
                return await next(actionName, params, opts);
    
            }.bind(this);
        },
    
    };
    

    【讨论】:

      猜你喜欢
      • 2020-06-24
      • 2019-01-24
      • 2016-05-16
      • 2020-02-29
      • 2022-11-03
      • 2022-11-30
      • 2018-08-11
      • 2018-11-29
      • 2016-02-14
      相关资源
      最近更新 更多