Passport.js is an authentication middleware for Node.js that can be used in Express-based web applications. It is highly flexible and modular, offering a set of strategies to authenticate requests. In this guide, we’ll cover how to implement Passport in an Express application for user authentication.
Prerequisites
- Node.js and npm installed
- Basic knowledge of Express
- An existing Express application
The Steps
Step 1: Install Passport and its Strategy
First, install Passport and the strategy of your choice (e.g., Local Strategy for username and password authentication) using npm:
npm install passport passport-local
Step 2: Create Passport Strategy
Configure the passport strategy for your application. For the Local Strategy, you’ll need to create a strategy that defines how users will be authenticated.
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
// Your authentication logic goes here
}
));
Step 3: Configure Express to Use Passport
Initialize Passport and configure it to manage sessions:
const express = require('express');
const passport = require('passport');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
Step 4: Define Serialization and Deserialization
Serialize user information to the session and deserialize it when requests are made:
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
// Find the user using the id
});
Step 5: Set Up Authentication Routes
Create routes for login and registration using the Local Strategy:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
})
);
Complete Code Example
Below is an example of how you can put all the steps together to create a simple authentication mechanism using Express and Passport.
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const app = express();
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
function(username, password, done) {
// User authentication logic goes here
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
// User deserialization logic here
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: 'Invalid username or password.'
})
);
app.listen(3000, function() {
console.log('Server started on port 3000.');
});
Conclusion
In this article, we walked through the steps required to add authentication to an Express application using Passport.js. By following these steps, you can implement a range of authentication strategies catered to the needs of your project.