Modify headers of proxied request

user375566 picture user375566 · Jun 18, 2013 · Viewed 16.1k times · Source

I'm IP restricting a pure client-side CORs demo application which interacts with an authenticated third-party API. I've got a "middleware" server running which I use to proxy requests from the CORs app to the third-party API, but I am having trouble injecting Basic Authentication credentials into those proxied requests.

isAllowed = (req, res, next) -> # Do IP check here.

base64Encode = (unencoded) -> new Buffer(unencoded or '').toString 'base64'

app.all "/demoproxy/*", isAllowed, (req, res) ->

  req.url = "/" + req.url.split("/").slice(2).join("/")

  userPass = base64Encode "#{process.env.DEMO_USERNAME}:#{process.env.DEMO_PASSWORD}"

   # This doesn't work.
   # res.setHeader 'Authorization',  "Basic #{userPass}"

   # This doesn't work either.
   ###res.oldWriteHead = res.writeHead

   res.writeHead = (statusCode, headers) ->

     headers = { }
     headers['Authorization'] = "Basic #{userPass}"
     res.oldWriteHead statusCode, headers###

    proxy = new httpProxy.HttpProxy
      target:
        host: 'remote-api.com'
        port: 80

    proxy.proxyRequest req, res

What is the proper way to do this?

Answer

cengebretson picture cengebretson · Jun 20, 2013

I think you want to set the authorization header on the request (req) object in this case, not the response (res). If remote-api.com is what needs to be authenticated against then it needs to know that with the request you send to it. Maybe try the following before making the proxy.proxyRequest request

req.headers["authorization"] = "Basic #{userPass}"

With the req object there isn't a setHeader function, the headers property is just a javascript object/map. Hope that helps out...