I'm using http-proxy as it comes with vite and I want to mock a real proxy, which validates a JWT token and uses basic authentication to communicate with the APIs.
what I have:
const configure: ProxyOptions["configure"] = (proxy, options) => {
proxy.on("proxyReq", function (proxyReq, req, res, options) {
console.log(options, proxyReq.getHeader("authorization"));
const [tokenType, token] =
proxyReq.getHeader("authorization")?.toString().split(" ") || [];
if (tokenType !== "Bearer" || !token) {
res.writeHead(401, { "Content-Type": "text/plain" });
res.write(
JSON.stringify({
error: "unauthorized",
error_description: "Invalid or missing access token",
}),
);
res.end();
return;
} else {
proxyReq.removeHeader("authorization");
}
});
};
export default defineConfig({
plugins: [react()],
server: {
open: true,
proxy: {
"/api/service1": {
target: {
protocol: "http",
auth: `user1:pass1`,
host: "localhost",
port: 3700,
},
changeOrigin: true,
configure,
},
"/api/service2": {
target: {
protocol: "http",
auth: `user2:pass2`,
host: "localhost",
port: 3600,
},
changeOrigin: true,
configure,
},
"/api/service3": {
target: {
protocol: "http",
auth: `user3:pass3`,
host: "localhost",
port: 3800,
},
changeOrigin: true,
configure,
},
},
},
proxyReq.removeHeader("authorization"); removes the header send from the react application, but doesn't add the basic auth defined in auth.