Open In App

Explain the use of passport.js for authentication in Express applications.

Authentication is an important aspect of maintaining the overall security of the application. As Express.js is the server-side language, it is important to secure the application with authentication. So we can use Passport.js which is the authentication middleware that has a modular way to implement the authentication strategies which includes the OAuth, username/password, and more authentication features.

Prerequisites

What is Passport.js Middleware?

Passport.js is the middleware that has the functions that are executed during the request-handling tasks. Using this we can integrate different authentication strategies like local authentication using usernames and passwords, OAuth, OpenID, and more strategies. This middleware is integrated into the Express.js applications which allows us to define the route and enforce the authentication at each endpoint.



Steps to use Passport.js middleware in Express:

Step 1: In the first step, we will create the new folder by using the below command in the terminal.

mkdir folder-name
cd folder-name

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.



npm init-y

Step 3: Now, we will install all the dependencies for our project using the below command.

npm install express passport passport-local express-session

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "passport": "^0.7.0",
    "passport-local": "^1.0.0"
}

Role of passport.js in Express Application Authentication:

Example: Write the following code in the app.js file




// app.js
const express = require('express');
const pass = require('passport');
const localAuth = require('passport-local').Strategy;
const sess = require('express-session');
const app = express();
// configuring the passport.js middlware
pass.use(new localAuth(
    (username, password, done) => {
        // demo credentials
        if (username === 'admin' && password === 'gfg') {
            return done(null, { id: 1, username: 'user' });
        } else {
            return done(null, false,
                { message: 'Hey Geek! Incorrect username or password.' });
        }
    }
));
pass.serializeUser((user, done) => {
    done(null, user.id);
});
pass.deserializeUser((id, done) => {
    // user retrival
    const user = { id: 1, username: 'user' };
    done(null, user);
});
// express middleware
app.use(express.urlencoded({ extended: true }));
app.use(sess(
    {
        secret: 'gfg',
        resave: false,
        saveUninitialized: false
    }));
app.use(pass.initialize());
app.use(pass.session());
// defining routes
app.get('/', (req, res) => {
    res.send('<h1>Passport.js Authentication Example</h1>');
});
app.get('/login', (req, res) => {
    res.send('<h1>Login Page</h1><form action="/login" method="post">' +
        'Username: <input type="text" name="username"><br>' +
        'Password: <input type="password" name="password"><br>' +
        '<input type="submit" value="Login"></form>'
    );
});
app.post('/login',
    pass.authenticate('local', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    })
);
app.get('/profile', isAuthenticated, (req, res) => {
    res.send(
        `<h1>Welcome ${req.user.username}!
        </h1><a href="/logout">Logout</a>`
    );
});
app.get('/logout', (req, res) => {
    req.logout((err) => {
        if (err) {
            return next(err);
        }
        res.redirect('/');
    });
});
// middleware to check if the user is authenticated
function isAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/login');
}
// starting the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on
    http://localhost:${PORT}`
    );
});

Step To run the application: Start the server by using the below command.

node app.js

Output:


Article Tags :