← Back to blog

Implementing Session Authentication with Passport

Passport is a popular authentication middleware for Node.js applications. It provides a simple and easy-to-use API for implementing different authentication strategies, including local strategy, which is used for authenticating users with a username and password. In this blog, we will explore how to use Passport with local strategy to implement session authentication in a Node.js application.

Session authentication is a popular authentication mechanism in web applications, where the user’s session is stored on the server-side, and a unique session ID is sent to the client’s browser as a cookie. The session ID is used to authenticate the user in subsequent requests. Passport makes it easy to implement session authentication with local strategy.

To get started, we need to install the necessary dependencies. We will be using the following packages:

  • passport: The core Passport library
  • passport-local: The local strategy plugin for Passport
  • express-session: A middleware for managing sessions in Express
typescript
npm install passport passport-local express-session

Next, we will configure Passport to use the local strategy for authentication. In this example, we will be using a simple array of user objects to store user credentials. In a real-world application, you would use a database to store user information.

typescript
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
// User data store
const users = [
{ id: 1, username: 'john', password: 'password' },
{ id: 2, username: 'jane', password: 'password' }
];
// Local strategy configuration
passport.use(new LocalStrategy(
(username, password, done) => {
// Find user with matching username
const user = users.find(u => u.username === username);
if (!user) {
return done(null, false, { message: 'Incorrect username' });
}
// Check if password is correct
if (user.password !== password) {
return done(null, false, { message: 'Incorrect password' });
}
// Authentication successful
return done(null, user);
}
));

In the above code, we define a users array containing user objects with their usernames and passwords. We then configure the local strategy using passport.use(). The LocalStrategy constructor takes a callback function with the signature (username, password, done).

In the callback function, we search for the user with the given username in the users array. If a user is found, we check if the password is correct. If the authentication is successful, we call done(null, user) to indicate that the user is authenticated. If the authentication fails, we call done(null, false, { message: 'Incorrect username or password' }) to indicate that the authentication failed with an error message.

Next, we will configure the session middleware using express-session. This middleware creates a session object for each user and stores it on the server-side. We will be using an in-memory session store for simplicity.

typescript
const session = require('express-session');
const app = require('express')();
// Session middleware configuration
app.use(session({
secret: 'my-secret-key',
resave: false,
saveUninitialized: false
}));
// Passport middleware initialization
app.use(passport.initialize());
app.use(passport.session());

In the above code, we configure the session middleware using express-session. We pass a secret key to the middleware to encrypt the session data. We also set resave and saveUninitialized to false to optimize the session storage.

We then initialize the Passport middleware using passport.initialize() and passport.session(). The passport.initialize() middleware initializes Passport and the passport.session()

We then initialize the Passport middleware using passport.initialize() and passport.session(). The passport.initialize() middleware initializes Passport and the passport.session() middleware adds support for persistent login sessions.

We can now define the login and logout routes in our application. In the login route, we will use the passport.authenticate() middleware to authenticate the user with the local strategy.

typescript
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));

In the above code, we define a POST route /login that authenticates the user using the passport.authenticate() middleware. We pass the local strategy as the first argument to passport.authenticate(). We also pass an options object that configures the middleware to redirect the user to the home page on successful authentication and to the login page on failed authentication. We also set failureFlash to true to enable flash messages.

In the logout route, we can simply call req.logout() to log out the user and destroy their session.

typescript
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});

We can now protect the routes that require authentication using the req.isAuthenticated() middleware. This middleware checks if the user is authenticated and calls the next middleware if they are, or redirects them to the login page if they are not.

typescript
app.get('/', (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
});
app.get('/profile', (req, res, next) => {
if (req.isAuthenticated()) {
res.render('profile');
} else {
res.redirect('/login');
}
});

In the above code, we protect the / and /profile routes by checking if the user is authenticated using req.isAuthenticated(). If the user is authenticated, we call the next middleware to render the requested page. If the user is not authenticated, we redirect them to the login page.

We have now implemented session authentication using Passport with local strategy in our Node.js application. Passport provides a flexible and easy-to-use API for implementing different authentication strategies, making it a popular choice for authentication in Node.js applications.

Enjoyed this post? Read the next one ↗