http-proxy-middleware icon indicating copy to clipboard operation
http-proxy-middleware copied to clipboard

Authenticating proxy based on target URL

Open glenjamin opened this issue 8 years ago • 1 comments

I've got my proxy working, but there are some URLs that I know the backend will return 403 unauthorized for depending on the API path and the properties of the current user - which is available in my existing session.

I'm trying to figure out where the best place to put such logic would be, I can write a function shouldBeAllowed(apiPath, userSession), but I can't find a spot where this would work.

If I pass it as the context argument, then I get the path before re-writes - which isn't the end of the world but seems a bit untidy.

If I use this function instead onProxyReq, I have all the information I need but I can't see how to abort the proxy request.

Any ideas?

Setup

  • http-proxy-middleware: 0.17.3
  • server: express 4.14.0

proxy middleware configuration

  app.use("/api", proxy({
    target: config.apiServer,
    pathRewrite: {"^/api": ""},
    xfwd: true,
    secure: true,
    changeOrigin: true,
    logLevel: "silent",
    headers: {
      cookie: ""
    },
    onProxyReq: (proxyReq, req) => {
      const user: User = req.session.user;
      // Convert session authentication into API authentication
      proxyReq.setHeader("Authorization", buildAPIAuth(user));
      req.log.info(
        {method: proxyReq.method, path: proxyReq.path},
        "proxying request"
      );
    }
  }));

glenjamin avatar Feb 20 '17 11:02 glenjamin

Sorry for the late reply @glenjamin .

Did you try using multiple middleware to achieve the result? Basically use/write a different middleware to add the authentication, before proxying the request.

chimurai avatar May 05 '17 12:05 chimurai