Skip to content

Instantly share code, notes, and snippets.

@LB-Digital
Created December 12, 2018 21:07
Show Gist options
  • Save LB-Digital/8ecda710b5d36f713877dac2743664ec to your computer and use it in GitHub Desktop.
Save LB-Digital/8ecda710b5d36f713877dac2743664ec to your computer and use it in GitHub Desktop.
Basic auth header of a subdomain on NodeJS with Express
/** Password protect a subdomain on ExpressJS
* Uses HTTP Basic authorization... https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
* with the WWW-Authenticate header... https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
*
* 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 'beta.domain.com' 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
noAuth();
}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
noAuth();
}
}
}else{ // user not visiting from specified subdomain, so just route their request normally
next();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment