var session = require('express-session');
var express = require('express');
var passport = require('passport');
var passportHttp = require('passport-http');
var DigestStrategy = require('passport-http').DigestStrategy;
var app = express();
var pages = {
'/': 'Home',
'/page1': 'Page 1',
'/page2': 'Page 2',
'/signout': 'Sign-Out',
};
var users = {
u1: {username: 'u1', password: 'p1'},
u2: {username: 'u2', password: 'p2'}
};
function userExists(username) {
return users[username] !== undefined;
}
function getUser(username) {
return users[username];
}
function makePage(path) {
return '<h1>'+pages[path]+'</h1>\n<ul>'+
Object.keys(pages).map(function(key) {
if(key === path) return '';
return '<li><a href="'+key+'">'+pages[key]+'</a></li>';
}).join('\n')+
'</ul>';
}
app.use(session({
name: 'session',
path: '/',
secret: 'secret',
saveUninitialized: true,
resave: true,
rolling: false,
cookie: { secure: false }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new DigestStrategy({ qop: 'auth' },
function(username, cb) {
console.log('DigestStrategy - username: %s', username);
if(!userExists(username)) return cb(null, false);
var user = getUser(username);
return cb(null, user, user.password);
})
);
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(id, done) {
var user = getUser(id);
if(user === undefined) return done(new Error('User not found'));
done(null, user);
});
app.use(passport.authenticate('digest', { session: true }));
app.use(function(req, res, next) {
console.log('[%s] > req.user: %s', req.url, JSON.stringify(req.user));
return next();
});
var plainPage = function(req, res, next) {
res.send(makePage(req.url)+'<br>Signed in as: '+req.user.username);
};
app.get('/', plainPage);
app.get('/page1', plainPage);
app.get('/page2', plainPage);
app.get('/signout', function(req, res, next) {
req.logout();
res.status(401);
res.send(makePage(req.url));
});
var server = app.listen(8080, 'localhost', function (err) {
console.log('Server listening on localhost:8080');
});
Basic example for "full site" authentication using HTTP Basic Authentication with node.js, express and passport.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.