0

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.

1
  • Appears to be a bug with vite in the bundled http-proxy Commented Jun 28 at 4:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.