Search code examples
expressexpress-gateway

Run custom functions in express-gateway


I have this configuration in the gateway.config.yml (Express-Gateway api):

 - bo
    policies:
      - jwt:
        - action:
            secretOrPublicKeyFile: './key.pem'
            checkCredentialExistence: false

Everything works fine, but I want the client to encode/encrypt a token that it is being sent to make sure even if I have the token storage on the localstorage no one can use it because it will need to be signed by the client.

The only problem with this is, how can I run a code to decode/decrypt the token before Express-Gateway jwt policy try to validate the token?

Because express-gateway can use middlewares like any other express application I think this is possible, but not an idea on how to do it.

I created this policy that will help me, but how can I integrate it with the express-gateway api:

const cryptojs = require("crypto-js");
module.exports = {
    name: 'decode',
    policy: (actionParams) => {
      return (req, res, next) => {
        const tokenHeader = req.header('Authorization');
        const tokenArray = tokenHeader.split(' ');
        const tokenCifer = tokenArray[1];
        const bytes  = cryptojs.AES.decrypt(tokenCifer, 'superkeyperm'); //CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
        var token = bytes.toString(cryptojs.enc.Utf8);
        req.headers.authorization = `Bearer ${token}`;
        next() // calling next policy
      };
    }
};

Solution

  • I think what you're interested is writing a plugin which is nothing more than a collection of additional middleware and condition you can stack in Express Gateway, where you can put your own logic.

    Check out the docs at https://www.express-gateway.io/docs/plugins/