Passport.js is a popular authentication middleware for Node.js, and the JSON Web Token (JWT) strategy is commonly used for stateless authentication. Here's a step-by-step guide on how to use Passport.js with the JWT strategy in a Node.js application:
Install Required Packages: Make sure you have Node.js installed, and create a new Node.js project. Then, install the necessary packages:
bashnpm init -y npm install express passport passport-jwt jsonwebtoken
Set Up Express:
Create a basic Express application in your index.js
file:
javascriptconst express = require('express');
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwt = require('jsonwebtoken');
const app = express();
const PORT = process.env.PORT || 3000;
// Set up JSON parsing middleware
app.use(express.json());
// Initialize Passport
app.use(passport.initialize());
// Dummy user data (replace this with your user database)
const users = [
{ id: 1, username: 'john_doe', password: 'password123' }
];
// Configure JWT Strategy
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'your_secret_key' // Change this to a secret key for your application
};
passport.use(new JwtStrategy(jwtOptions, (payload, done) => {
// Check if the user exists
const user = users.find(u => u.id === payload.id);
if (user) {
return done(null, user);
} else {
return done(null, false);
}
}));
// Route for generating a JWT token (login)
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Authenticate the user (replace this with your authentication logic)
const user = users.find(u => u.username === username && u.password === password);
if (user) {
// Generate a JWT token
const token = jwt.sign({ id: user.id }, jwtOptions.secretOrKey);
res.json({ token });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
// Protected route that requires a valid JWT token
app.get('/protected', passport.authenticate('jwt', { session: false }), (req, res) => {
res.json({ message: 'You have access to this protected route!' });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Note: Replace the your_secret_key
placeholder with a secure secret key for your application.
Test the Authentication:
node index.js
/login
with a JSON payload containing the username
and password
.Authorization
header with the value Bearer YOUR_TOKEN
for subsequent requests to the /protected
route.This is a basic example, and you may need to adapt it to your specific authentication requirements and user data storage. Additionally, consider using environment variables for sensitive information like secret keys.