13 กันยายน 2560

Add pop-up to ask for username and password [node.js] [express.js] [authorization]

To authorize user with basic username and password pop-up like this is really easy on express.js

You just put this code before doing the routes configuration.

var app = express();
//-----------------------------------
// attach middlewares
//-----------------------------------
app.use(function(req, res, next) {
// define username and password here
var auth = { username: 'username', password: 'password' };

var b64auth = (req.headers.authorization || '').split(' ')[1] || '';
var [username, password] = new Buffer(b64auth, 'base64').toString().split(':');
// Verify username and password are correct
if (!username || !password || username !== auth.username || password !== auth.password) {
res.set('WWW-Authenticate', 'Basic realm="nope"');
return res.status(401).send('Unauthorized');
} else {
return next();
}
});


ไม่มีความคิดเห็น:

แสดงความคิดเห็น

บทความยอดนิยม (ล่าสุด)

บทความยอดนิยม (1 ปีย้อนหลัง)