How to protect proxy with guards in NestJS

2.3k views Asked by At

Using http-proxy-middleware (which uses http-proxy) I was able to create proxy to an internal (hidden from outside) url and get expected response.

However, since this is middleware approach, I am not able to apply any existing Guards (eg, JWT, Role etc) to this proxy.

NetJS Guards documentation mentions that Guards are run after each middleware.

Without re-implementing all the Guards as middleware, is there any way that I can protect this proxy route with existing Guards?

Thanks in advance.

2

There are 2 answers

1
Jay McDoniel On

It wouldn't be possible to use Nest guards, as you said, this is a middleware. The only thing you could do to protect the proxy route is to add a middleware for the proxy route before the proxy middleware is installed. If you're setting up the proxy middleware in main.ts it would look something like this

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use('proxy-route', (req, res, next) => {
    if (passCondition) {
      return next();
    }
    return next(new UnauthorizedException());
  }
  app.use(proxyMiddleware);
  await app.listen(port);
}
1
Sebastián Figueroa Morán On

this works to replace Guard logic (cookie with JWT)

app.use(
    createProxyMiddleware('/proxy', {
      target: API_SERVICE_URL,
      changeOrigin: true,
      pathRewrite: {
        '^/proxy': '/', // remove base path
      },
      onProxyReq: (proxyReq, req: Request, res: Response, options) => {
        const { cookie } = req.headers;

        if (!cookie) {
          res.status(403).json({ message: 'Not token provided' });
          return;
        }

        const token = cookie.replace('Authentication=', '');

        if (!token) {
          res.status(403).json({ message: 'Not token provided' });
          return;
        } else {
          jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
            if (err) {
              res.status(403).json({ message: 'Invalid token' });
              return;
            }
          });
        }
      },
    }),
    cookieParser(),
  );