To implement authentication and authorization in a Node.js application using Express.js, you can use the following steps:
**Step 1: Install necessary packages**
First, you need to install the required packages for authentication and authorization. For this example, we will use:
1. [Express](https://www.npmjs.com/package/express) - Web framework for Node.js
2. [Passport](https://www.npmjs.com/package/passport) - Authentication middleware for Node.js
3. [Passport-local](https://www.npmjs.com/package/passport-local) - Local username and password authentication
4. [Bcryptjs](https://www.npmjs.com/package/bcryptjs) - Secure hashing for storing passwords
5. [Express-session](https://www.npmjs.com/package/express-session) - Middleware for handling sessions in Express.js
Install these packages with npm:
npm install express passport passport-local bcryptjs express-session
**Step 2: Set up Express and Passport**
Create an ’app.js’ (or ’index.js’) file:
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const session = require('express-session');
const app = express();
// Set up session middleware
app.use(session({
secret: 'your-secret-key', // Replace with your own secret key
resave: false,
saveUninitialized: false,
}));
// Set up passport middleware
app.use(passport.initialize());
app.use(passport.session());
// Set up bodyParser to handle POST data
app.use(express.urlencoded({ extended: true }));
**Step 3: Implement User model**
Create a simple user model (you can replace this with your own database implementation):
const users = [
{
id: 1,
username: 'john',
password: '$2a$10$cFikkgjKslE6LcDS6rGAK.KdYU.q2YPHLq3y5Q2kuDU.ssie81Kpa', // hashed version of 'password'
}
];
// Replace these functions with database queries in a real-world application
function findUser(userId) {
return users.find(user => user.id === userId);
}
function findUserByUsername(username) {
return users.find(user => user.username === username);
}
function validatePassword(user, password) {
return bcrypt.compareSync(password, user.password);
}
**Step 4: Configure Passport**
Set up the local strategy for Passport:
passport.use(new LocalStrategy((username, password, done) => {
const user = findUserByUsername(username);
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!validatePassword(user, password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
}));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
done(null, findUser(id));
});
**Step 5: Implement routes for authentication**
Add routes for login, logout, and register:
app.get('/login', (req, res) => {
res.send(`
<form action="/login" method="post">
<input name="username">
<input type="password" name="password">
<button>Login</button>
</form>
`);
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
}));
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
// Implement register route if needed.
// When creating a new user, make sure to hash the password using bcrypt:
// const hashedPassword = bcrypt.hashSync(password, 10);
**Step 6: Implement authorization**
Create a simple middleware to ensure a user is authenticated:
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next(); // The user is authenticated, proceed to the next route handler
}
res.redirect('/login'); // Redirect to the login page if not authenticated
}
app.get('/private', ensureAuthenticated, (req, res) => {
res.send('Only authorized users can see this page.');
});
**Step 7: Start the server**
Start the Express server:
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
With these steps in place, you should have a basic authentication and authorization system using Node.js, Express, and Passport. To integrate this into a real-world application, replace the example user model and database queries with the appropriate logic for your database.