Skip to content

Instantly share code, notes, and snippets.

@peterhpchen
Last active September 16, 2018 16:17
Show Gist options
  • Save peterhpchen/c4a47028ec27f086836aa1f6410eb65b to your computer and use it in GitHub Desktop.
Save peterhpchen/c4a47028ec27f086836aa1f6410eb65b to your computer and use it in GitHub Desktop.
Node.js Basic Auth which Using Custom Authorization Type to Prevent Browser Basic Auth Popup.
const http = require('http');
// const BASIC_AUTH = 'xBasic'; // Use Custom Authorization Type to Prevent Browser Basic Auth Popup
const BASIC_AUTH = 'Basic';
const USER_NAME = 'admin';
const PASSWORD = 'admin';
function unauthorizedRes(res) {
// res.statusCode = 400; // Use Status Code Except 401
res.statusCode = 401;
res.setHeader('WWW-Authenticate', `${BASIC_AUTH} realm="Secure Area"`);
res.write('401 Unauthorized');
res.end();
}
const server = http.createServer((req, res) => {
const auth = req.headers['authorization'];
console.log(`Authorization Header: ${auth}`);
if (!auth) { // Without Authorization Header
unauthorizedRes(res);
return;
}
if (!auth.startsWith(`${BASIC_AUTH} `)) { // Wrong Authorization Type
unauthorizedRes(res);
return;
}
const encodeAuth = auth.substring(`${BASIC_AUTH} `.length);
console.log(`Encode Authorization: ${encodeAuth}`);
const decodeAuth = Buffer.from(encodeAuth, 'base64').toString();
console.log(`Decode Authorization: ${decodeAuth}`);
const userPasswordArray = decodeAuth.split(':');
if (userPasswordArray.length !== 2) { // Wrong Authorization Format
unauthorizedRes(res);
return;
}
const [userName, password] = userPasswordArray;
console.log(`User Name: ${userName}, Password: ${password}`)
if (userName === USER_NAME && password === PASSWORD) { // User Name and Password Correct
res.statusCode = 200;
res.write('200 OK');
res.end();
return;
}
// User Name or Password Wrong
unauthorizedRes(res);
});
server.listen(12345);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment