Last active
July 29, 2024 18:25
-
-
Save shisama/0406fbc1a54d69350d6d17a31fc3d1e2 to your computer and use it in GitHub Desktop.
Node.js Proxy Server with Basic Auth Sample
This file contains 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 { parse } = require("basic-auth"); | |
const { PROXY_USERNAME, PROXY_PASSWORD } = process.env; | |
const PROXY_PORT = process.env.PROXY_PORT || 8000; | |
const check = (credentials) => { | |
return ( | |
credentials && | |
credentials.username === PROXY_USERNAME && | |
credentials.pass === PROXY_PASSWORD | |
); | |
}; | |
const proxy_server = http.createServer(function (request, response) { | |
const credentials = parse(request.headers["proxy-authorization"]); | |
if (!check(credentials)) { | |
response.statusCode = 401; | |
response.end("Access denied"); | |
} | |
const options = { | |
port: 80, | |
host: request.headers["host"], | |
method: request.method, | |
path: request.url, | |
headers: request.headers, | |
}; | |
const proxy_request = http.request(options); | |
proxy_request.on("response", function (proxy_response) { | |
proxy_response.on("data", function (chunk) { | |
response.write(chunk, "binary"); | |
}); | |
proxy_response.on("end", function () { | |
response.end(); | |
}); | |
response.writeHead(proxy_response.statusCode, proxy_response.headers); | |
}); | |
request.on("data", function (chunk) { | |
proxy_request.write(chunk, "binary"); | |
}); | |
request.on("end", function () { | |
proxy_request.end(); | |
}); | |
}); | |
proxy_server.listen(PROXY_PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment