ExpressGateway / express-gateway

A microservices API Gateway built on top of Express.js
https://www.express-gateway.io
Apache License 2.0
2.97k stars 344 forks source link

Mutate req object from plugin #995

Closed code-angels closed 4 years ago

code-angels commented 4 years ago

I'm quite struggling with the following problem.
I have created a small plugin because I want custom jwt middleware verification on certain endpoints.

The policy works as expected, but for some reason I'm not able to set a new property 'user' object on the req object in a way that it is propagated to the actual service endpoint. I need this user object to perform certain tasks in my service endpoints.

Policy:

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

module.exports = {

  name: 'jwt-policy',

  policy: (actionParams) => {
    return (req, res, next) => {
      const jwt = getJwtFromCookies(req) || getJwtFromHeader(req);

      try {
        req.user = verifyToken(jwt);
        console.log('req.user', req.user);
        next() // calling next policy

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

      }

    };
  }

};

This works, and it correctly logs the req.user object here.

Added to the pipeline:

  - jwt-policy:
      condition: # this action is executed only if path is exactly /v1/auth
        name: pathMatch
        pattern: /v1/auth/*

But as mentioned, the req.user object is not propagated to the actual service endpoint.
Perhaps what I try to achieve is possible through the standard jwt plugin, but it isn't all that clear how this simple case may be achieved. Any help with this?

code-angels commented 4 years ago

Fixed this by using this in the plugin:

req.egContext.authUser = verifyToken(jwt);

And defining a request-transformer:

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