How to use Passport.js for authentication in an Express.js application



Image not found!!

Passport.js is a popular authentication middleware for Node.js applications, especially in the context of Express.js. It provides a flexible and modular way to handle authentication, supporting various authentication strategies (e.g., local, OAuth, OpenID, etc.).

Here's a step-by-step guide on how to use Passport.js for authentication in an Express.js application:

  1. Install Dependencies: Ensure you have Node.js and npm installed. Create a new Express.js application and install the necessary packages:

    bash
    npm init -y
    npm install express passport passport-local express-session
  2. Setup Express Application: Create your Express application and configure it with necessary middleware:

    javascript
    const express = require('express'); const session = require('express-session'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const app = express(); // Middleware setup app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); // Your routes and other middleware can go here... app.listen(3000, () => { console.log('Server is running on port 3000'); });
  3. Configure Passport: Set up Passport with a local strategy for username and password authentication. You'll need to define a function that checks the user's credentials.

    javascript
    passport.use(new LocalStrategy( (username, password, done) => { // Replace this with your own user authentication logic if (username === 'yourUsername' && password === 'yourPassword') { return done(null, { id: 1, username: 'yourUsername' }); } else { return done(null, false, { message: 'Incorrect username or password' }); } } )); passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser((id, done) => { // Replace this with your own logic to fetch user from the database const user = { id: 1, username: 'yourUsername' }; done(null, user); });
  4. Configure Authentication Routes: Set up routes for login, logout, and user authentication. Customize these routes based on your application needs.

    javascript
    app.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login', failureFlash: true, }) ); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get('/dashboard', isAuthenticated, (req, res) => { res.send(`Hello, ${req.user.username}!`); }); function isAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login'); }
  5. Create Login Form: Create an HTML form for user login (e.g., views/login.ejs).

    html
    <!-- login.ejs --> <form action="/login" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <button type="submit">Login</button> </form>
  6. Run Your Application: Start your Express application and visit http://localhost:3000 in your browser. Customize and expand the authentication logic according to your application's requirements.

    bash
    node your-app.js

This is a basic setup using Passport.js for local authentication in an Express.js application. Depending on your needs, you might want to explore other Passport.js strategies for OAuth, OpenID, and more. Additionally, consider integrating with a database for storing user information securely.