Implementing authentication in a web application is crucial to identifying users and restricting access to certain resources. Express.js, a popular web framework for Node.js, provides a straightforward way to set up authentication.
Step-by-Step Guide
Step 1: Initialize Project
npm init -y
npm install express bcryptjs passport passport-local express-session body-parser mongoose
Step 2: Set Up Express App
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const app = express();
app.use(session({ secret: 'mysecret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
Step 3: Configure Passport
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
// Define a local strategy for Passport
passport.use(new LocalStrategy(
function(username, password, done) {
// User findOne logic here...
// Call done(null, user) if credentials are valid
// Call done(null, false) if credentials are invalid
}
));
// Serialize and deserialize user instances
passport.serializeUser(function(user, done) { done(null, user.id); });
passport.deserializeUser(function(id, done) { done(null, { id }); });
Step 4: Implement Routes
const express = require('express');
const router = express.Router();
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: false
}));
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
module.exports = router;
Complete Code Example
// Full express app setup with authentication
// Place this code in a server.js file
const express = require('express');
const bcrypt = require('bcryptjs');
const passport = require('passport');
// Express app initialization...
// Passport configuration...
// Application routes...
// Server start...
app.listen(3000, () => console.log('Server running on port 3000'));
Conclusion
In this tutorial, we’ve outlined the steps to set up user authentication in an Express.js application with Passport.js. You can expand upon this foundation to include more sophisticated features like OAuth, JWT tokens, or multi-factor authentication, depending on your requirements.