首页 > 解决方案 > Express-gateway 为快速微服务应用程序创建新的插件/策略

问题描述

我正在创建一个 express JS 微服务架构,并使用 express-gateway 作为 API 网关。

我可以通过 express gateway 公开我的服务和端点,其中一项服务(书籍)有 2 个角色(管理员、用户)和 2 个不同的登录 startegies(管理员使用 JWT,用户使用 Firebase auth)。

我使用 express-gateway 提供的 JWT 成功地保护了管理端点 /v1/admin,现在我想创建一个策略 / 插件(我不明白其中的区别)以涉及我的 CheckIfAuthenticatedFirebase 中间件来保护我的用户端点 /v1 /用户。

所以我需要一些帮助来了解我是否必须创建插件或策略以及执行它的步骤。

这是我的gateway.config.yml

http:
  port: 8080
admin:
  port: 9876
  host: localhost
apiEndpoints:
  bookAdmin:
    path: '/v1/admin*'
  bookUser:
    path: '/v1/user*'
serviceEndpoints:
  book:
    url: 'http://localhost:5000'
policies:
  - cors
  - log
  - proxy
  - jwt
  - request-transformer
pipelines:
  bookAdminPipeline:
    apiEndpoints:
      - bookAdmin
    policies:

      -
        cors:
          action:
            origin: '*'
            methods: 'GET,HEAD,PUT,PATCH,POST,DELETE'   
      -
        jwt:
          action:
            secretOrPublicKey: 'JWTKey'
            checkCredentialExistence: false

      -
        proxy:
          action:
            serviceEndpoint: book
  bookUserPipeline:
    apiEndpoints:
      - bookUser
    policies:

      -
        cors:
          action:
            origin: '*'
            methods: 'GET,HEAD,PUT,PATCH,POST,DELETE'   
      -
        proxy:
          action:
            serviceEndpoint: book

这是我的firebase-middleware.js

var admin = require('../authentication/firebase');

 getAuthToken = (req, res, next) => {
    if (
      req.headers.authorization &&
      req.headers.authorization.split(' ')[0] === 'Bearer'
    ) {
      req.authToken = req.headers.authorization.split(' ')[1];
    } else {
      req.authToken = null;
    }
    next();
  };


checkIfAuthenticated = (req, res, next) => {
   getAuthToken(req, res, async () => {
      try {
        const { authToken } = req;
        const userInfo = await admin
          .auth()
          .verifyIdToken(authToken);
        req.authId = userInfo.uid;
        return next();
      } catch (e) {
        return res
          .status(401)
          .send({ error: 'You are not authorized to make this request' });
      }
    });
  };

  module.exports = checkIfAuthenticated

非常感谢

标签: node.jsapiexpressmicroservicesexpress-gateway

解决方案


您必须创建一个策略并通过插件调用它。

  1. 在您的插件目录中创建一个文件夹,假设文件夹名称为 auth。
  2. 在该 auth 文件夹中,创建文件夹策略和文件 manifest.js
  3. 在策略文件夹中创建一个文件 auth.js。
  4. 在 manifest.js 里面写这段代码
module.exports = {
        version: '1.2.0',
        init: function (pluginContext) {
           let policy = require('./policies/auth')
           pluginContext.registerPolicy(policy)
        },
        policies:['auth'], // this is for CLI to automatically add to "policies" whitelist in gateway.config
        schema: {  // This is for CLI to ask about params 'eg plugin configure customer-auth'
            "$id":"https://express-gateway.io/schemas/plugins/blacklist.json"
        }
    }
  1. 您的 auth.js 文件应如下所示
module.exports = {
  name: 'auth',
  schema: {
    $id: 'http://express-gateway.io/schemas/policies/example-policy.json',
    type: 'object',
    properties: {
      baseUrl: {
        type: 'string',
        format: 'url',
        default: ''
      }
    }
  },
  policy: (actionParams) => {
    const that = this;
    return (req, res, next) => {
      // your custom logic

    };
  }
};

现在您只需将清单路径放入 system.config.yml

plugins:      
  auth:
    package: "../../../plugins/auth/manifest.js"

最后一步将在策略部分的 gateway.config.yml 文件中声明此策略

policies:
  - basic-auth
  - cors
  - expression
  - request-transformer
  - key-auth
  - log
  - oauth2
  - proxy
  - rate-limit
  - auth

现在您可以像使用任何其他策略一样轻松使用它。:)


推荐阅读