Last active
June 28, 2016 19:32
-
-
Save firedfox/7f41fff1f77b45ef91809bbe9dbef1e1 to your computer and use it in GitHub Desktop.
node proxy with basic auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const httpProxy = require('http-proxy'); | |
const port = 8128; | |
const username = 'username'; | |
const password = 'password'; | |
const authBuffer = Buffer.from(username + ':' + password, 'ascii'); | |
const authToken = 'Basic ' + authBuffer.toString('base64'); | |
const proxy = httpProxy.createProxyServer({}); | |
const server = http.createServer((req, res) => { | |
var authHeader = req.headers['proxy-authorization']; | |
if (authHeader === authToken) { | |
console.log('[%s] [forward] %s', new Date, req.url); | |
proxy.web(req, res, { | |
target: req.url | |
}); | |
} | |
else { | |
console.error('[%s] [auth failed %s] %s', new Date, authHeader, req.url); | |
res.statusCode = 404; | |
res.end(); | |
} | |
}); | |
server.timeout = 600000; | |
server.on('clientError', (err, socket) => { | |
console.error('[%s] [error %s] %s', new Date, err.message); | |
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); | |
}); | |
console.log("listening on port %d", port) | |
server.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment