Securing Your Express REST API with Passport.js
As web applications grow, secure authentication becomes essential to protect sensitive data and prevent unauthorized access. In this article, we’ll explore how to secure a Node.js API using Passport.js and JSON Web Tokens (JWT) for stateless, token-based authentication. We’ll also use PostgreSQL for persistent storage of user data, providing a robust, scalable setup ideal for modern applications.
Why Use Passport.js and JWT for Node.js?
Passport.js is a powerful, flexible middleware for handling authentication in Node.js applications. When paired with JWTs, it enables scalable, stateless authentication without the need to manage session data. JWTs are particularly useful in mobile-friendly applications where maintaining server-side sessions is impractical.
Advantages
Using Passport.js, PostgreSQL and JWTs offers several key benefits:
- Passport.js simplifies integration of various authentication strategies.
- JWTs allow for stateless authentication, meaning no session management overhead.
- PostgreSQL offers a reliable, ACID-compliant database for securely storing user credentials.
In this article, we will be using PostgreSQL as our database. You can maintain your database in any database management system. For a convenient deployment option, consider cloud-based solutions like Rapidapp, which offers managed PostgreSQL databases, simplifying setup and maintenance.
Create a free database in Rapidapp in seconds here
Step-by-Step Guide to Securing Your Express API
Project Initialization and Dependencies
Before diving into the code, ensure you have:
- Node.js and npm installed.
- PostgreSQL database ready for storing user data.
- Basic understanding of JavaScript and Node.js.
To start, initialize a new Node.js project and install required dependencies:
mkdir express-rest-api-jwt && cd express-rest-api-jwt
npm init -y
npm install express passport passport-jwt jsonwebtoken pg bcrypt dotenv
We’re using:
- express: Web framework for Node.js.
- passport and passport-jwt: Middleware and JWT strategy for authentication.
- jsonwebtoken: For generating and verifying JWTs.
- pg: PostgreSQL client for Node.js.
- bcrypt: For securely hashing passwords.
- dotenv: For environment variable management.
Configuring PostgreSQL for User Data
Set up a PostgreSQL database to store user information. Connect to your PostgreSQL instance and create a new database and table. If you are using Rapidapp, the database is already created there.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL
);
In this setup, the users table stores a unique email
and a hashed password
. Next, create a .env
file to manage sensitive configuration:
DATABASE_URL=postgresql://username:password@host:5432/secure_app
JWT_SECRET=your_jwt_secret_key
Remember to replace username, password, and other values with your actual credentials.
Building the User Authentication Logic
Password Hashing
To securely store user passwords, use bcrypt to hash them before saving to the database. This prevents storing plaintext passwords.
const bcrypt = require('bcrypt');
const saltRounds = 10;
// Hashing function
async function hashPassword(password) {
return await bcrypt.hash(password, saltRounds);
}
User Registration Endpoint
Create a registration endpoint to handle new user signups. Hash the user’s password and save it in the database.
const express = require('express');
const app = express();
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
app.use(express.json());
app.post('/register', async (req, res) => {
const { email, password } = req.body;
const passwordHash = await hashPassword(password);
try {
await pool.query('INSERT INTO users (email, password_hash) VALUES ($1, $2)', [email, passwordHash]);
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
res.status(500).json({ error: 'User registration failed' });
}
});
User Login and JWT Generation
Create a login endpoint to validate credentials. If valid, generate a JWT for the user.
const jwt = require('jsonwebtoken');
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
const user = result.rows[0];
if (user && await bcrypt.compare(password, user.password_hash)) {
const token = jwt.sign({ id: user.id, email: user.email }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
Implementing Passport.js with JWT Strategy
Configure Passport.js to use the JWT strategy. Create a Passport configuration file and define the JWT strategy using passport-jwt
.
const passport = require('passport');
const { Strategy, ExtractJwt } = require('passport-jwt');
passport.use(new Strategy({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET
}, async (jwtPayload, done) => {
const result = await pool.query('SELECT * FROM users WHERE id = $1', [jwtPayload.id]);
const user = result.rows[0];
return user ? done(null, user) : done(null, false);
}));
app.use(passport.initialize());
With this configuration, Passport extracts the JWT from the Authorization
header and verifies it using our secret key.
Creating Protected Routes
Now that Passport is set up, you can protect specific routes by requiring authentication. Passport will verify the JWT before allowing access to these routes.
app.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
res.json({ message: `Welcome ${req.user.email}` });
});
In this example, the /profile
route requires a valid JWT. If authentication succeeds, the request proceeds; otherwise, it’s rejected.
Serving the API
Finally, start the Express server to serve the API:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Testing the Authentication Workflow
Register a New User
To create a new user, make a POST request to the /register
endpoint with the user’s email and password.
curl -X POST http://localhost:3000/register \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "password": "securepassword"}'
If successful, this will return:
{
"message": "User registered successfully"
}
Login with the Registered User
To log in, make a POST request to the /login
endpoint with the same email and password. This will return a JWT if the
credentials are correct.
curl -X POST http://localhost:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "password": "securepassword"}'
If successful, you’ll receive a response similar to this:
{
"token": "your_jwt_token_here"
}
Access the Protected Profile Endpoint
To access the protected /profile
endpoint, you’ll need to include the JWT in the Authorization header as a Bearer token.
Replace your_jwt_token_here
with the actual token you received from the login step:
curl -X GET http://localhost:3000/profile \
-H "Authorization: Bearer your_jwt_token_here"
If the JWT is valid, you should receive a response like:
{
"message": "Welcome [email protected]"
}
If the token is missing or invalid, you’ll likely get a 401 Unauthorized response:
{
"error": "Unauthorized"
}
Conclusion
Using Passport.js and JWT for authentication in a Node.js application provides a secure, stateless setup ideal for scaling. Combined with PostgreSQL, this setup efficiently handles user management while maintaining security best practices. With these foundations, you’re well-equipped to build secure, scalable applications.
You can find the complete source code for this project on GitHub.