How to add a authorization header to a user request and the proxy it to another server api with express

Viewed 577

You see this is what happen, the client side has a cookie with http only flag and inside of it a JWT that will be use by the API server to authorize the request , the thing is that the JWT should be in a Authorization header so I am using a middle server to catch the client request, extract the JWT from the cookie, set the Authorization Header within client request and then forward the request to the API server to fetch the data.

The main problem is that I dont know how properly set the header from the middle server or even if that is posible, because every time I try to forward to the API server this last got the Authorization header undefined that I supposedly set in the middleware server.

So, how can I set a Authorization Header and forward to another server properly?, the middle server and the API server both uses NodeJS and Express.

This is so far the code from the middle server I have (dont worry about the cookie extraction part, this is just testing propuses):

const proxy = require('express-http-proxy');
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 8083;

app.use(cors());
// app.use(express.json());

app.use('/graphql',
(req, res, next) => {
    req.headers['Authorization'] = `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZFVzZXIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkphY2sifQ.5y3IhB4i_THfKZr5BYe6dZruhOUbQt7SRT_rrssApCo`;
    next()
},
proxy('http://localhost:8081/graphql'));

app.listen(PORT, () => console.log(`http://localhost:${PORT}`));
1 Answers

After a while looking for another answers and reading the documentation documentation I found that the package express-http-proxy has the exactly the property I needed, that is proxyReqOptDecorator. When you declare the proxy middleware the second arguament is a object whit diferent options like propertiess, the proxyReqOptDecorator recive a function with 2 parameters: proxyReqOpts to atach any property to the request object and the original request object (as far as I did understand).

So, in order to solve the problem and set the Authorization header to the request object before forawrd I did change the code adding the property proxyReqOptDecorator:

app.post('/graphql',
proxy('http://localhost:8081/graphql',{
    proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
        proxyReqOpts.headers['Authorization'] = `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZFVzZXIiOiI2MDNjYzM0ZTM2ZTk0MjI0MTNkYzNmZDUiLCJuYW1lIjoiRGFuaWVsIn0._ZJytuJJoG8RM6kki6YZcMlYAh7M0zAZWE54x7i3nhs`;
        return proxyReqOpts;
      }
}));

Well thats it, thats solved the problem. I still don't know why the first code didn't work and if there are any other ways to do this but I expect that work for you too.

Related