How to use Passport.js in Express app
Using Passport.js in an Express application allows you to implement various authentication strategies with ease. Passport is a popular middleware for authentication in Node.js applications and supports a variety of strategies for authenticating requests.
Step-by-Step Guide to Using Passport in Express
-
Install Necessary Packages:
Install
passport
,passport-local
,express-session
, andbody-parser
(if not already installed):npm install express passport passport-local express-session body-parser
-
Set Up Express Application:
Create a basic Express application and configure Passport:
const express = require('express'); const session = require('express-session'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const bodyParser = require('body-parser'); const app = express(); // Use body-parser middleware app.use(bodyParser.urlencoded({ extended: false })); // Set up session middleware app.use(session({ secret: 'your-secret-key', // Replace with your secret key resave: false, saveUninitialized: false })); // Initialize Passport and use it with session app.use(passport.initialize()); app.use(passport.session()); // Example users database const users = [ { id: 1, username: 'test', password: 'password' } ]; // Configure Passport Local Strategy passport.use(new LocalStrategy( function(username, password, done) { const user = users.find(u => u.username === username); if (!user) { return done(null, false, { message: 'Incorrect username.' }); } if (user.password !== password) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); } )); // Serialize user to store user ID in session passport.serializeUser(function(user, done) { done(null, user.id); }); // Deserialize user by ID stored in session passport.deserializeUser(function(id, done) { const user = users.find(u => u.id === id); done(null, user); }); // Route to display login form app.get('/login', (req, res) => { res.send(` <form action="/login" method="post"> <div> <label>Username:</label> <input type="text" name="username"/> </div> <div> <label>Password:</label> <input type="password" name="password"/> </div> <div> <button type="submit">Log In</button> </div> </form> `); }); // Route to handle login form submission app.post('/login', passport.authenticate('local', { successRedirect: '/profile', failureRedirect: '/login', failureFlash: false }) ); // Route to display profile if authenticated app.get('/profile', (req, res) => { if (!req.isAuthenticated()) { return res.redirect('/login'); } res.send(`Hello ${req.user.username}, you are authenticated!`); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
-
Explanation:
- Session Middleware: Configures session handling with
express-session
. - Passport Middleware: Initializes Passport and configures it to use sessions.
- User Database: A simple array of users for demonstration purposes.
- LocalStrategy: Configures Passport to use the local strategy for authentication.
- The
LocalStrategy
function checks if the username and password match a user in the array.
- The
- Serialization and Deserialization: Handles storing user information in the session and retrieving it.
- Login Route: Displays a simple login form.
- Login Form Handling: Authenticates user credentials using
passport.authenticate()
. - Profile Route: Displays the user profile if authenticated.
- Session Middleware: Configures session handling with
Published on: Jun 29, 2024, 04:24 PM