Reputation: 332
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.
Upvotes: 1
Views: 2675
Reputation: 21
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(), );
Upvotes: 2
Reputation: 70221
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);
}
Upvotes: 1