[英]Modify headers of proxied request
我限制了與經過身份驗證的第三方API交互的純客戶端CORs演示應用程序的IP。 我正在運行“中間件”服務器,該服務器用於將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
正確的方法是什么?
我認為您想在這種情況下在請求(req)對象上設置授權標頭,而不是在響應(res)上設置。 如果需要對remote-api.com進行身份驗證,則它需要通過發送給它的請求來知道這一點。 在發出proxy.proxyRequest
請求之前,請嘗試以下proxy.proxyRequest
req.headers["authorization"] = "Basic #{userPass}"
對於req
對象,沒有setHeader函數,headers屬性只是一個javascript對象/映射。 希望能幫上忙...
這是一些對我有用的代碼,例如:
# 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 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.