expressexpress-gateway

Express gateway set custom policy path wildcard


I've created a basic plugin that does some custom Jwt verification, and sets a 'user' object on the req in a policy.

It's not really relevant, but the middleware plicy looks like this:

const { getJwtFromCookies, getJwtFromHeader } = require("../lib/jwt");
const { verifyToken } = require("../lib/jwt");


module.exports = {

  name: 'jwt-policy',

  policy: (actionParams) => {
    return (req, res, next) => {
      console.log('test plugin');
      const jwt = getJwtFromCookies(req) || getJwtFromHeader(req);

      try {
        req.user = verifyToken(jwt);
        console.log('plugin:', req.user);

      } catch (e) {
        res.send(401);

      }

      next() // calling next policy
    };
  }
};

In the api gateway, the plugin is properly called when I don't specify a path.
But it doesn't get called when I put the path with a wildcard like this (I don't want to call the plugin on all the routes, neither do I want a single 'exact' path:

  user:
    apiEndpoints:
    - user
    policies:
      - jwt-policy:
          condition: # this action is executed only if path is exactly /v1/auth
            name: pathExact
            path: '/v1/auth/*'

What is the correct declaration for this / where do I find this in the docs?


Solution

  • From the source code I've seen that the required format is:

      - jwt-policy:
          condition: 
            name: pathMatch
            pattern: /v1/auth/*
    

    I'm still dealing with the problem that properties set on the req object from the plugin don't propagate to the actual endpoint. This is still a problem for my case.

    Edit: second problem fixed by using the egContext property in the plugin:

    req.egContext.authUser = verifyToken(jwt);
    

    And defining a request-transformer:

      - request-transformer:
        - action:
            body:
              add:
                authUser: req.egContext.authUser
    

    It is not very desirable to have this property added to the request body rather than to the req object immediately, but I don't think that this is currently supported by Express Gateway. I opened a feature request for this.