Explain the working of passport.js

Working of Passport.js:

  • Passport.js is a popular authentication middleware for Node.js. It simplifies the implementation of authentication strategies, such as local authentication, OAuth, and OpenID. Here's how we can set up the Passport.js to work with the JWT authentication.

Setup and Configuration:

  • Initialize Passport.js with JWT authentication strategy and configure it with a secret key and token extraction method.

User Authentication:

  • Implement a login route to validate user credentials and generate a JWT token using jsonwebtoken.sign().

Protected Routes:

Define routes that require authentication and protect them using Passport.js middleware with the JWT strategy.

  • Passport.js verifies the JWT token, attaches user information to the request (req.user), and passes control to the route handler.

User Access:

  • Access authenticated user information from req.user in protected route handlers and perform authorization checks.

Token Expiration and Renewal:

  • Optionally, set token expiration using the expiresIn option when signing tokens and implement mechanisms for token renewal or re-authentication.

Error Handling:

  • Implement error handling middleware to manage authentication-related errors like invalid tokens or unauthorized access attempts.

Code snippet

const express = require('express');
const passport = require('passport');
const passportJWT = require('passport-jwt');
const JWTStrategy = passportJWT.Strategy;
const ExtractJWT = passportJWT.ExtractJwt;
const jwt = require('jsonwebtoken');
const app = express();
// Sample user database (In a real application, this would be a database)
const users = [
    { id: 1, username: ‘user1’, password: ‘password1’ },
    { id: 2, username: ‘user2’, password: ‘password2’ }
];
// Secret key for signing JWT tokens
const secretKey = ‘secret’;
// JWT options for strategy
const jwtOptions = {
    jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
    secretOrKey: secretKey
};
// JWT strategy for authentication
passport.use(new JWTStrategy(jwtOptions, (jwtPayload, done) => {
   const user = users.find(u => u.id === jwtPayload.id);
   if (!user) {
     return done(null, false, { message: ‘User not found’ });
   }
     return done(null, user);
}));
// Route for generating JWT token (Login)
app.post(‘/login’, (req, res) => {
    const { username, password } = req.body;
    const user = users.find(u => u.username === username && u.password === password);
    if (!user) {
        return res.status(401).json({ message: ‘Invalid credentials’ });
    }
    const token = jwt.sign({ id: user.id }, secretKey, { expiresIn: ‘1h’ });
    res.json({ token });
});
// Protected route
app.get(‘/profile’, passport.authenticate(‘jwt’, { session: false }), (req, res) => {
    res.json({ message: Welcome, ${req.user.username}! });
});
// Start server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(Server is running on http://localhost:${PORT});
});

In this example:

  • We set up Express, Passport.js, passport-jwt, and jsonwebtoken middleware.
  • We define a simple in-memory user database for demonstration purposes.
  • We configure a JWT strategy for authentication using Passport.js.
  • We define a route for user login, where a JWT token is generated upon successful authentication.
  • We protect a route (‘/profile’) using Passport.js middleware with the JWT strategy.
  • When accessing the ‘/profile’ route with a valid JWT token, the user’s profile information is returned.