Skip to content

Instantly share code, notes, and snippets.

Created December 12, 2018 21:07
What would you like to do?
Basic auth header of a subdomain on NodeJS with Express
/** Password protect a subdomain on ExpressJS
* Uses HTTP Basic authorization...
* with the WWW-Authenticate header...
* By then checking if the user is visting from the given subdomain, you know they are authorized.
* I use this concept to password protect beta site features that aren't yet released publicly, on which
* certain pages are only accessible via the password protected '' url
const config = {
subDomain: 'beta',
desc: 'Access to Beta site',
username: 'admin',
password: 'password'
router.use(( req,res,next )=>{
if (req.subdomains[0] == SubDomain){
var auth = req.headers['authorization']; // get the auth header, '<type> <base64 credentials>'
function noAuth(){
res.statusCode = 401; // 401:unauthorized
res.setHeader('WWW-Authenticate', 'Basic realm="' + config.desc + '"'); // Basic authentication
res.end('<html><body>' + config.desc + ' requires authentication!</body></html>');
if (!auth){ // no auth header has been set
}else{ // auth header has been set
var tmp = auth.split(' '); // split auth type from credentials
var buf = Buffer.from(tmp[1], 'base64'); // create buffer from base64 creds
var creds = buf.toString().split(':'); // creds[0] = username, creds[1] = password
if (creds[0] === config.username && creds[1] === config.password){ // VALID
next(); // move onto routing the users request
}else{ // INVALID
}else{ // user not visiting from specified subdomain, so just route their request normally
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment