修改代理请求的标头

5

我正在对一个纯客户端的CORS演示应用进行IP限制,该应用与经过身份验证的第三方API进行交互。我运行了一个“中间件”服务器,用它来代理从CORS应用程序发送到第三方API的请求,但是我在向这些代理请求中注入基本身份验证凭据时遇到了困难。

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

什么是正确的方法?
2个回答

13

我想你希望在这种情况下设置请求(req)对象上的授权标头,而不是响应(res)。如果需要对remote-api.com进行身份验证,则需要通过您发送给它的请求来知道这一点。在发出proxy.proxyRequest请求之前,可以尝试以下方法。

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

使用req对象时,没有setHeader函数,头信息属性只是一个JavaScript对象/映射。希望这能帮到你...


所以,我尝试了那个。但它与其他基本身份验证不同?问题已更新。 - user375566
1
你尝试过同时设置req.headers ['authorization']吗?根据node HTTP文档(http://nodejs.org/api/http.html#http_message_headers),headers对象全部小写,因此如果在设置大写头时它不起作用,也许代理只查看小写版本。 - david

0

这里有一些对我有效的代码,作为示例:

# Demo server requiring basic authentication
servAuth = require("http").createServer (req, res) ->
  if auth = req.headers?.authorization
    res.statusCode = 200
    res.end "Good job, you sent '#{auth}'"
  else
    res.statusCode = 401
    res.end "How about you authenticate first?"
servAuth.listen(8090)

# Proxy server which checks the IP address and then proxies the request
servProxy = require("http-proxy").createServer (req, res, proxy) ->
  checkIP req, (err, isOK) ->
    # something wrong happened even with the IP address checking
    if err
      res.statusCode = 500
      res.end "Sorry, everything got fargled", "ascii"
    # IP address not allowed
    else if not isOK
      res.statusCode = 403
      res.end "You ain't from around here, are you?", "ascii"
    # all good, proxy the request with basic auth added
    else
      userPass = new Buffer("#{process.env.USERNAME}:#{process.env.PASSWORD}", "ascii")
      userPass = userPass.toString("base64")
      req.headers.authorization = "Basic #{userPass}"
      proxy.proxyRequest req, res, {
        host: "localhost"
        port: 8090
      }
servProxy.listen(8080)

# asynchronous IP address checking
checkIP = (req, done) ->
  # TODO: implement whatever custom IP checking
  # this example just says everything is OK
  done( null, true )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接